I'm new to React. I've a MealList component to which I'm passing a set of props, based on which it make a data call and updates an array of meals, which I display in a table.
const MealList = (props) => {
const [meals, setMeals] = useState([]);
useEffect(() => {
const fetchMeals = async (userId, fromDate, toDate, fromTime, toTime) => {
...
return resp;
};
fetchMeals(localStorage.getItem('user_id'), props.fromDate, props.toDate, props.fromTime, props.toTime).then(r => {
setMeals([...meals, ...r.data])//The fetched data is stored in an array here.
});
}, [props]);
console.log(props.fromDate);
return (
<div style={{width: '70%'}}>
...
<Table striped bordered hover>
<thead>
<tr>
...
</tr>
</thead>
<tbody>
{meals.map((meal, index) => (<Meal key={meal.id} count={index +1} meal={meal}/>))}//And displayed here
</tbody>
</Table>
</div>
)
};
The problem I'm facing is that using the spread syntax setMeals([...meals, ...r.data])
appends to the existing list everytime MealList is updated via the props.
My question is how can I set the meals array back to null and then update only the new values? I've tried this:
fetchMeals(localStorage.getItem('user_id'), props.fromDate, props.toDate, props.fromTime, props.toTime).then(r => {
setMeals([]);
setMeals([...meals, ...r.data])
});
But this doesn't work either.
setMeals([...r.data])
?setMeals([])
right beforesetMeals([...meals, ...r.data])
. Just call it once with the data you want set into that state object.meals
state object the old objects? If so, why are you adding it back into state along with the response? If you want to update the meal state with just the response from an api, instead ofsetMeals([...meals, ...resp.data])
trysetMeals(resp.data)
which is functionally equal tosetMeals([...resp.data])
.