I have a Dashboard
component which has 3 children Search
, MealList
and UserData
.
I have 4 state variables, fromDate
, toDate
, fromTime
and toTime
which are initially set to null inside the Dashboard
.
These are passed down to the MealList
component as props.
const Dashboard = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [calories, setCalories] = useState("");
const [fromDate, setFromDate] = useState(null);
const [toDate, setToDate] = useState(null);
const [fromTime, setFromTime] = useState(null);
const [toTime, setToTime] = useState(null);
useEffect(async () =>{
const data = await fetchUserData(localStorage.getItem('email'));
localStorage.setItem('user_id', data['id']);
setUsername(data['username']);
setEmail(data['email']);
setCalories(data['calories']);
}, []);
const updateList = (fd, td, ft, tt) =>{
setFromDate(fd);
setToDate(td);
setFromTime(ft);
setToTime(tt);
};
console.log(fromDate);
return (
<div>
<Navigation/>
<div className="wrapper">
<div style={{display: 'flex', flexFlow: 'row wrap'}}>
<UserData username={username} email={email} calories={calories}/>
<Search onSubmit={updateList}/>
</div>
<MealList fromDate={fromDate} toDate={toDate} fromTime={fromTime} toTime={toTime}/>
</div>
</div>
)
};
export default Dashboard;
The MealList component fetches data based on these 4 state variables.
const MealList = (props) => {
const [meals, setMeals] = useState([]);
useEffect(async () => {
const mealsData = await fetchMeals(localStorage.getItem('user_id'), props.fromDate, props.toDate, props.fromTime, props.toTime);
setMeals([...meals, ...mealsData]);
}, []);
return (
<div style={{width: '70%'}}>
<h3 style={{color: 'grey', fontSize: '1.4em', fontWeight: '700', marginBottom: '1em'}}><FontAwesomeIcon
icon={faPlusCircle} style={{color: '#007bff', marginRight: '0.5em'}}/> ADD MEAL</h3>
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Meal</th>
<th>Calories</th>
<th>Time</th>
<th>Date</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}
</tbody>
</Table>
</div>
)
};
export default MealList;
These state variables are updated in the from submission inside Search
, which calls the updateList
function inside Dashboard
.
1. How do I pass these values back and re-render MealList everytime these updateList
is called?
2. How do I nullify the meals array inside MealList and add the new set of values fetched?
This I believe will add values to the existing array.
const [meals, setMeals] = useState([]);
setMeals([...meals, ...mealsData]);