Saturday, 4 January 2020

Setting an array to null and then updating it in useEffect React

I'm new to React, thus the question. 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=>
            ...
            <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. Any help appreciated.



from Setting an array to null and then updating it in useEffect React

No comments:

Post a Comment