简体   繁体   中英

How to fetch more data and store it in the state correctly in React?

I want to fetch more data from my api. I'm using the spread operator but It doesn't add to the state in a correct form.

After fetching I get this array. On array[5] it adds an extra array. Instead of that I want it to add to the existing ones.

0: {route_id: 7, price: 16760, distance: 111, shift_time: 20, max_load: 250, …}
1: {route_id: 2, price: 0, distance: 0, shift_time: 0, max_load: 100, …}
2: {route_id: 3, price: 0, distance: 0, shift_time: 0, max_load: 55, …}
3: {route_id: 4, price: 0, distance: 111, shift_time: 20, max_load: 240, …}
4: {route_id: 1, price: 0, distance: 0, shift_time: 0, max_load: 57, …}
5: (5) [{…}, {…}, {…}, {…}, {…}]

My code:

 axios(config)
        .then(function (response) {
            
            setRefreshing(false)
            setCardLoading(false)
            console.log(response.data);
            if(response.data.status_code === 200) {
                setRoutes([...routes, response.data.response])
            }
        })

Seems like you need to spread your response also, like:

setRoutes([...routes, ...response.data.response]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM