import React, { useState, useEffect } from "react"; import { View, StyleSheet, Text,…
- User
import React, { useState, useEffect } from "react"; import { View, StyleSheet, Text, Modal, TextInput, ScrollView, Dimensions, Pressable, TouchableOpacity } from "react-native"; import ScheduleEditor from "./scheduleEditor"; import Animated, { SlideInDown, SlideOutDown, FadeIn, FadeOut, } from 'react-native-reanimated'; import moment from "moment"; import Timetable from "react-native-calendar-timetable"; import Rectangle from "../common/rectanglev2"; import ButtonComp from "../common/Button";
const CALENDAR_WIDTH = 807; const CALENDAR_HEIGHT = 670;
const AnimatedPressable = Animated.createAnimatedComponent(Pressable);
const EditSchedule = () => { // Set up the date range for Monday to Friday of the current week const [from] = React.useState(moment().startOf('week').add(1, 'days').toDate()); const [till] = React.useState(moment().startOf('week').add(5, 'days').toDate()); const [isOpen, setOpen] = useState(false); const [isAddingSchedule, setIsAddingSchedule] = useState(false); const [scheduleName, setScheduleName] = useState(''); const [tempSchedules, setTempSchedules] = useState([]); const [currentSchedule, setCurrentSchedule] = useState( { id: 0, name: "Default Schedule", items: [ { title: 'Monday', startDate: moment().startOf('week').add(1, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(1, 'days').hour(10).toDate(), }, { title: 'Tuesday', startDate: moment().startOf('week').add(2, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(2, 'days').hour(10).toDate(), }, { title: 'Wednesday', startDate: moment().startOf('week').add(3, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(3, 'days').hour(10).toDate(), }, { title: 'Thursday', startDate: moment().startOf('week').add(4, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(4, 'days').hour(10).toDate(), }, { title: 'Friday', startDate: moment().startOf('week').add(5, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(5, 'days').hour(10).toDate(), }, ] });
const range = { from, till }; // Set up the event data // the data below will eventually be fetched from the database const [allSchedules, setAllSchedules] = React.useState([ { id: 0, name: "Default Schedule", items: [ { title: 'Monday', startDate: moment().startOf('week').add(1, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(1, 'days').hour(10).toDate(), }, { title: 'Tuesday', startDate: moment().startOf('week').add(2, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(2, 'days').hour(10).toDate(), }, { title: 'Wednesday', startDate: moment().startOf('week').add(3, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(3, 'days').hour(10).toDate(), }, { title: 'Thursday', startDate: moment().startOf('week').add(4, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(4, 'days').hour(10).toDate(), }, { title: 'Friday', startDate: moment().startOf('week').add(5, 'days').hour(8).toDate(), endDate: moment().startOf('week').add(5, 'days').hour(10).toDate(), }, ] }, // You can add more schedules here ]); // Combine allSchedules and tempSchedules const combinedSchedules = [...allSchedules, ...tempSchedules]; const handleScheduleCreation = (selectedDays, startHour, startMinute, endHour, endMinute) => { const daysIndex = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; console.log(selectedDays, 'selectedDays'); const newItems = selectedDays.map((day) => { return { title: day, startDate: moment().startOf('week').add(daysIndex.indexOf(day) + 1, 'days').hour(startHour).minute(startMinute).toDate(), endDate: moment().startOf('week').add(daysIndex.indexOf(day) + 1, 'days').hour(endHour).minute(endMinute).toDate() }; }); setCurrentSchedule({ ...currentSchedule, items: newItems }); // add the new schedule into last element of tempSchedules setTempSchedules( prevArray => [ ...prevArray.slice(0, -1), { ...prevArray[prevArray.length - 1], items: newItems } ]); }; // ... existing code ...useEffect(() => { console.log('Current Schedule updateds:', currentSchedule); }, [currentSchedule]);
useEffect(() => { console.log('Temp Schedules updated:', tempSchedules); }, [tempSchedules]);// ... rest of the component ...
const CustomHeader = ({ date }) => ( <View style={styles.headerContainer}> <Text style={styles.headerText}>{moment(date).format('ddd')}</Text> </View> ); const calculateDayIndex = (date) => { return moment(date).isoWeekday(); }; const addNewSchedule = () => { if (scheduleName.trim()) { setTempSchedules([...tempSchedules, { id: allSchedules.length, name: scheduleName, // items will be initialized as an empty array because the user will be adding events later items: [] }]); setCurrentSchedule([]); setScheduleName(''); setIsAddingSchedule(false); } }; const handleSave = () => { const scheduleToSave = tempSchedules.find(schedule => schedule.id === currentSchedule.id); if(scheduleToSave){ const updatedSchedules = allSchedules.map((schedule) => { return schedule.id === scheduleToSave.id ? { ...schedule, items: currentSchedule.items } : schedule; }); setAllSchedules(updatedSchedules); console.log('schedules updated', updatedSchedules); } else { console.log('schedule not found'); } }; const handleScheduleViewChange = (scheduleName) => { const selectedSchedule = combinedSchedules.find(schedule => schedule.name === scheduleName); if (selectedSchedule) { setCurrentSchedule(selectedSchedule); } }; return ( <View style={styles.container}> <View style={styles.contentContainer}> <View style={styles.schedulesContainer}> <ScrollView horizontal showsHorizontalScrollIndicator={false}> {combinedSchedules.map((schedule, index) => ( <TouchableOpacity key={index} style={currentSchedule.name === schedule.name ? styles.activeSchedule : styles.schedule} onPress={() => handleScheduleViewChange(schedule.name)} > <Text style={currentSchedule.name === schedule.name ? styles.activeScheduleText : styles.scheduleText}> {schedule.name} </Text> </TouchableOpacity> ))} <TouchableOpacity style={styles.addScheduleButton} onPress={() => setIsAddingSchedule(true)} > <Text style={styles.addScheduleButtonText}>+</Text> </TouchableOpacity> </ScrollView> </View> {isAddingSchedule && ( <Animated.View style={styles.addScheduleInputContainer} entering={FadeIn.springify().damping(17)} exiting={FadeOut}> <TextInput style={styles.addScheduleInput} value={scheduleName} onChangeText={setScheduleName} placeholder="New Schedule Name" onSubmitEditing={addNewSchedule} /> <TouchableOpacity onPress={addNewSchedule} style={styles.addButton}> <Text style={styles.addButtonText}>Add</Text> </TouchableOpacity> <TouchableOpacity onPress={() => setIsAddingSchedule(false)} style={styles.cancelButton}> <Text style={styles.cancelButtonText}>Cancel</Text> </TouchableOpacity> </Animated.View> )} <View style={styles.outerCalendarContainer}> <Timetable items={currentSchedule.items} range={range} timeWidth={50} hourHeight={40} renderHeader={CustomHeader} renderItem={props => { const dayIndex = calculateDayIndex(props.item.startDate); return ( <Rectangle {...props} dayIndex={dayIndex} daysTotal={5} index={props.index} event={currentSchedule[dayIndex - 1]} // Pass the event data /> ); }} is12Hour={true} fromHour={8} toHour={18} style={styles.timetable} columnWidth={700 / 5 - 1} hideNowLine={true} /> </View> <View style={styles.searchButtonContainer}> { currentSchedule.items.length > 0 ? ( <ButtonComp title="Edit" buttonStyle={styles.searchButton} onPress={() => setOpen(true)} /> ) : ( <ButtonComp title="Create" buttonStyle={styles.searchButton} onPress={() => setOpen(true)} /> ) } <ButtonComp title="Save" buttonStyle={styles.searchButton} onPress={handleSave} /> </View> </View> {isOpen && ( <> <AnimatedPressable onPress={() => setOpen(false)} style={styles.backdrop} entering={FadeIn} exiting={FadeOut} /> <Animated.View style={styles.sheet} entering={SlideInDown.springify().damping(17)} exiting={SlideOutDown.springify().damping(17)}> <ScheduleEditor handleScheduleCreation={handleScheduleCreation} /> </Animated.View> </> )} </View> );};
import React, { useState } from "react"; import { View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { Picker } from '@react-native-picker/picker'; import Button from "../common/Button";
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; const hours = Array.from({length: 11}, (, i) => { const hour = (i + 8) % 12 || 12; // Convert to 12-hour format const period = (i + 8) < 12 ? 'AM' : 'PM'; // Determine AM/PM return
${hour.toString().padStart(2, '0')} ${period}; }); const minutes = Array.from({length: 60}, (, i) => i.toString().padStart(2, '0'));const ScheduleEditor = ({ handleScheduleCreation }) => { const [selectedDays, setSelectedDays] = useState([]); const [startHour, setStartHour] = useState('08'); const [startMinute, setStartMinute] = useState('00'); const [startPeriod, setStartPeriod] = useState('AM'); const [endHour, setEndHour] = useState('09'); const [endMinute, setEndMinute] = useState('00'); const [endPeriod, setEndPeriod] = useState('AM');
const toggleDay = (day) => { setSelectedDays(prevDays => prevDays.includes(day) ? prevDays.filter(d => d !== day) : [...prevDays, day] ); }; const convertTo24Hour = (hour, period) => { let hourInt = parseInt(hour); if (period === 'PM' && hourInt !== 12) { hourInt += 12; } return hourInt.toString().padStart(2, '0'); }; const handleSave = () => { const start24Hour = convertTo24Hour(startHour, startPeriod); console.log(start24Hour); const end24Hour = convertTo24Hour(endHour, endPeriod); console.log(end24Hour); handleScheduleCreation(selectedDays, start24Hour, startMinute, end24Hour, endMinute); }; return ( <View style={styles.container}> <View style={styles.dayButtonsContainer}> {days.map((day) => ( <TouchableOpacity key={day} style={[ styles.dayButton, selectedDays.includes(day) && styles.selectedDayButton ]} onPress={() => toggleDay(day)} > <Text style={[ styles.dayButtonText, selectedDays.includes(day) && styles.selectedDayButtonText ]}> {day} </Text> </TouchableOpacity> ))} </View> <View style={styles.timeContainer}> <View style={styles.pickerContainer}> <Text style={styles.pickerLabel}>Start Time</Text> <View style={styles.pickerRow}> <View style={styles.pickerWrapper}> <Picker selectedValue={startHour} onValueChange={(itemValue) => setStartHour(itemValue)} style={styles.picker} > {hours.map((hour) => ( <Picker.Item key={`start-hour-${hour}`} label={hour.split(' ')[0]} value={hour.split(' ')[0]} style={styles.pickerItem} /> ))} </Picker> </View> <Text style={styles.pickerSeparator}>:</Text> <View style={styles.pickerWrapper}> <Picker selectedValue={startMinute} onValueChange={(itemValue) => setStartMinute(itemValue)} style={styles.picker} > {minutes.map((minute) => ( <Picker.Item key={`start-minute-${minute}`} label={minute} value={minute} style={styles.pickerItem} /> ))} </Picker> </View> <View style={styles.AMPMContainer}> <TouchableOpacity style={[styles.AMPMButton, startPeriod === 'AM' && styles.activeAMPMButton]} onPress={() => setStartPeriod('AM')}> <Text style={startPeriod === 'AM' && styles.activeAMPMText}>AM</Text> </TouchableOpacity> <TouchableOpacity style={[styles.AMPMButton, startPeriod === 'PM' && styles.activeAMPMButton]} onPress={() => setStartPeriod('PM')}> <Text style={startPeriod === 'PM' && styles.activeAMPMText}>PM</Text> </TouchableOpacity> </View> </View> </View> <View style={styles.pickerContainer}> <Text style={styles.pickerLabel}>End Time</Text> <View style={styles.pickerRow}> <View style={styles.pickerWrapper}> <Picker selectedValue={endHour} onValueChange={(itemValue) => setEndHour(itemValue)} style={styles.picker} > {hours.map((hour) => ( <Picker.Item key={`end-hour-${hour}`} label={hour.split(' ')[0]} value={hour.split(' ')[0]} /> ))} </Picker> </View> <Text style={styles.pickerSeparator}>:</Text> <View style={styles.pickerWrapper}> <Picker selectedValue={endMinute} onValueChange={(itemValue) => setEndMinute(itemValue)} style={styles.picker} > {minutes.map((minute) => ( <Picker.Item key={`end-minute-${minute}`} label={minute} value={minute} /> ))} </Picker> </View> <View style={styles.AMPMContainer}> <TouchableOpacity style={[styles.AMPMButton, endPeriod === 'AM' && styles.activeAMPMButton]} onPress={() => setEndPeriod('AM')}> <Text style={endPeriod === 'AM' && styles.activeAMPMText}>AM</Text> </TouchableOpacity> <TouchableOpacity style={[styles.AMPMButton, endPeriod === 'PM' && styles.activeAMPMButton]} onPress={() => setEndPeriod('PM')}> <Text style={endPeriod === 'PM' && styles.activeAMPMText}>PM</Text> </TouchableOpacity> </View> </View> <View style={styles.buttonContainer}> <Button title="Apply" onPress={handleSave} style={styles.modalButtonContainer} buttonStyle={styles.modalButton}/> </View> </View> </View> </View> );};
The first piece of code is my scheduling interface. The second piece of code is modal I bring up to customize my shcheduling interface. I have a lot of state in the first piece of code but I am having trouble understanding the order of the state updates in an organized way in my mind. Could you systematically help me track how state is moving through both components and explain the fundamentals of state in react as reasoning behind the state updates. I want to get a clear picture of state in my mind for these components.
- Assistant
Certainly! Let's dive deep into how state is managed and updated within your two React components,
EditScheduleandScheduleEditor, to help you visualize the flow of data and understand the fundamentals of state in React.Overview
In your scheduling interface,
EditScheduleis the main component that manages schedules, whileScheduleEditoris a modal component used to create or edit schedule items (events). The state flows fromEditScheduletoScheduleEditorvia props and fromScheduleEditorback toEditSchedulevia callback functions.Let's break down each component and track the state updates systematically.
EditSchedule Component
State Variables
-
Date Range:
- from: Start date (Monday of the current week).
- till: End date (Friday of the current week).
-
UI State:
- isOpen: Controls the visibility of the
ScheduleEditormodal. - isAddingSchedule: Controls the visibility of the "Add Schedule" input field.
- scheduleName: Holds the name of the new schedule being added.
- isOpen: Controls the visibility of the
-
Schedules State:
- allSchedules: Array of saved schedules.
- tempSchedules: Array of schedules being edited or not yet saved.
- combinedSchedules: Combination of
allSchedulesandtempSchedulesfor display purposes. - currentSchedule: The schedule currently being viewed or edited.
Initial State Setup
-
Date Range: Calculated once and stored using
useState. Since dates don't change during component life, they are set and not updated. -
Schedules:
- allSchedules is initialized with a default schedule.
- tempSchedules starts as an empty array.
- currentSchedule is set to the default schedule.
State Flow and Updates
-
Adding a New Schedule:
- User Action: Clicks on the "Add Schedule" button (
isAddingScheduleis set totrue). - User Input: Enters a schedule name.
- State Update:
addNewSchedulefunction is called when the user presses "Add".
addNewSchedule Function:
const addNewSchedule = () => { if (scheduleName.trim()) { const newSchedule = { id: allSchedules.length + tempSchedules.length, name: scheduleName, items: [], }; setTempSchedules([...tempSchedules, newSchedule]); setCurrentSchedule(newSchedule); setScheduleName(''); setIsAddingSchedule(false); } };- Updates:
- Adds the new schedule to
tempSchedules. - Sets
currentScheduleto the newly added schedule. - Resets
scheduleNameand hides the input field.
- Adds the new schedule to
- User Action: Clicks on the "Add Schedule" button (
-
Selecting a Schedule:
- User Action: Clicks on a schedule from the list.
- State Update:
handleScheduleViewChangeis called with the selected schedule's name.
handleScheduleViewChange Function:
const handleScheduleViewChange = (scheduleName) => { const selectedSchedule = combinedSchedules.find( (schedule) => schedule.name === scheduleName ); if (selectedSchedule) { setCurrentSchedule(selectedSchedule); } };- Updates:
- Sets
currentScheduleto the selected schedule.
- Sets
-
Editing or Creating Schedule Items:
- User Action: Clicks the "Edit" or "Create" button, opening
ScheduleEditormodal (isOpenis set totrue). - State Update in Child: User selects days and times in
ScheduleEditor.
Data Flow from Child to Parent:
ScheduleEditorcallshandleScheduleCreation(passed via props) with the selected days and times.
- User Action: Clicks the "Edit" or "Create" button, opening
-
Updating Schedule Items:
- State Update:
handleScheduleCreationupdatescurrentScheduleandtempSchedules.
handleScheduleCreation Function:
const handleScheduleCreation = ( selectedDays, startHour, startMinute, endHour, endMinute ) => { const daysIndex = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; const newItems = selectedDays.map((day) => ({ title: day, startDate: /* computed start time */, endDate: /* computed end time */, })); setCurrentSchedule({ ...currentSchedule, items: newItems, }); setTempSchedules((prevArray) => prevArray.map((schedule) => schedule.id === currentSchedule.id ? { ...schedule, items: newItems } : schedule ) ); };- Updates:
currentSchedule.itemsis updated withnewItems.- The corresponding schedule in
tempSchedulesis updated.
- State Update:
-
Saving the Schedule:
- User Action: Clicks the "Save" button.
- State Update:
handleSaveis called to persist changes.
handleSave Function:
const handleSave = () => { const updatedSchedules = allSchedules.some( (schedule) => schedule.id === currentSchedule.id ) ? allSchedules.map((schedule) => schedule.id === currentSchedule.id ? currentSchedule : schedule ) : [...allSchedules, currentSchedule]; setAllSchedules(updatedSchedules); setTempSchedules((prev) => prev.filter((schedule) => schedule.id !== currentSchedule.id) ); };- Updates:
- If
currentScheduleexists inallSchedules, it's updated. - If not, it's added to
allSchedules. - The schedule is removed from
tempSchedulessince it's now saved.
- If
-
Reacting to State Changes:
- useEffect Hooks: Log changes whenever
currentScheduleortempSchedulesupdate.
useEffect(() => { console.log('Current Schedule updated:', currentSchedule); }, [currentSchedule]); useEffect(() => { console.log('Temp Schedules updated:', tempSchedules); }, [tempSchedules]); - useEffect Hooks: Log changes whenever
Rendering Based on State
- Schedules List: Renders
combinedSchedules, highlighting thecurrentSchedule. - Timetable: Renders events from
currentSchedule.items. - Buttons: "Edit" or "Create" button text changes based on whether
currentSchedule.itemshas events.
ScheduleEditor Component
State Variables
- selectedDays: Array of days the user has selected.
- startHour, startMinute, startPeriod: Start time components.
- endHour, endMinute, endPeriod: End time components.
State Flow and Updates
-
Selecting Days:
- User Action: Taps on day buttons to select/deselect days.
- State Update:
toggleDayfunction modifiesselectedDays.
toggleDay Function:
const toggleDay = (day) => { setSelectedDays((prevDays) => prevDays.includes(day) ? prevDays.filter((d) => d !== day) : [...prevDays, day] ); }; -
Selecting Time:
- User Action: Picks start and end times from pickers.
- State Update: Updates
startHour,startMinute,startPeriod,endHour,endMinute,endPeriod.
-
Applying Changes:
- User Action: Presses the "Apply" button.
- Data Flow: Calls
handleScheduleCreationprop with the selected days and times.
handleSave Function in ScheduleEditor:
const handleSave = () => { const start24Hour = convertTo24Hour(startHour, startPeriod); const end24Hour = convertTo24Hour(endHour, endPeriod); handleScheduleCreation( selectedDays, start24Hour, startMinute, end24Hour, endMinute ); };
React State Fundamentals Applied
-
State Isolated in Components:
ScheduleEditormanages its own state for user inputs.EditSchedulemanages schedules and application-wide state.
-
State Lifting:
- Data from
ScheduleEditorneeds to updateEditSchedule. - The
handleScheduleCreationfunction allowsScheduleEditorto pass data up.
- Data from
-
Unidirectional Data Flow:
- Parent passes
handleScheduleCreationto child. - Child calls this function to update parent's state.
- Ensures predictable and easier-to-track state changes.
- Parent passes
-
Asynchronous State Updates:
- State updates in React may be batched for performance.
- Using functional updates (e.g.,
setState((prev) => ...)) ensures we work with the latest state.
-
Side Effects with useEffect:
- Logging or any action that occurs due to state changes is handled in
useEffect.
- Logging or any action that occurs due to state changes is handled in
-
Rendering Based on State:
- The UI re-renders automatically when state updates.
- Components render differently based on the current state values.
Visualization of State Flow
-
Initial Load:
allSchedules: Contains one default schedule.tempSchedules: Empty.currentSchedule: Default schedule.
-
Adding a Schedule:
- New schedule added to
tempSchedules. currentScheduleupdated to the new schedule.
- New schedule added to
-
Editing Schedule Items:
- Open
ScheduleEditor. - User selections update local state in
ScheduleEditor. - On "Apply",
handleScheduleCreationupdatescurrentSchedule.itemsandtempSchedules.
- Open
-
Viewing Updates:
- Timetable reflects
currentSchedule.items. - User can see the events they've just created.
- Timetable reflects
-
Saving Changes:
- On "Save",
handleSavemoves the schedule fromtempSchedulestoallSchedules. - Removes the schedule from
tempSchedulessince it's now saved.
- On "Save",
Key Takeaways About React State
-
State Should Be Minimal and Relevant:
- Only store what's necessary.
- Avoid redundancy (e.g.,
combinedSchedulesis computed, not stored).
-
Use Functional Updates When State Depends on Previous State:
- Helps prevent issues due to asynchronous updates.
-
State Changes Cause Re-renders:
- Any update to state variables will cause the component to re-render and reflect changes in the UI.
-
Props for Data and Callbacks:
- Data flows down via props.
- Functions (callbacks) flow up from child to parent to update state.
Conclusion
By systematically tracking state in both components, you can see how user actions lead to state updates, which then trigger UI changes. Understanding the flow of data and control—from user interactions to state updates and re-renders—is crucial in React. Remember that state should be predictable and managed in a way that makes your application easy to reason about.
In your specific case, ensure that:
- State updates are correctly updating related variables.
- The logic for saving and updating schedules is consistent.
- Functional updates (
setState((prev) => ...)) are used when the new state depends on the previous state. - Components have clear responsibilities for managing their own local state versus shared state.
By keeping these principles in mind, you'll have a clearer picture of how state moves through your components, leading to a more maintainable and predictable codebase.
-