Home > Net >  Why state is not storing data correctly?
Why state is not storing data correctly?

Time:10-29

I am getting data through axios and storing that in a state

useEffect(() => {
  getCartItems();
}, []);

const [abc, setAbc] = useState([]);

const getCartItems = async () => {
  let data = await CartApi.get(`/${store.getState().auth.user.id}/`)
    .then(({ data }) => data);
  console.log('data =>', data)
  data.map(a => setAbc([...abc, a.item]))
}

I print the data variable in the console, and it gives the following output

data

But after that I store data.item in another state, but it is not storing first one. If I run console.log(abc) it shows only 24

abc

Why i'm not getting [32,24]

CodePudding user response:

Because you're reusing the same abc in every one of those calls to setAbc, so only the last of the items is actually added. Remember that the state setter doesn't change the abc constant you're using, it schedules a new call to your component function that will get the new value for abc from useState.

When updating data based on existing data, you should use the callback form. Also, there's no reason to make repeated setAbc calls, just make one with all the new data, see *** comments:

useEffect(() => {
    getCartItems();
},[]);
const[abc,setAbc]=useState([]);
const getCartItems = async () => {
    let data = await CartApi.get(`/${store.getState().auth.user.id}/`).then(({data})=>data);
    const items = data.map(({item}) => item);  // *** Get the items
    setAbc(abc => [...abc, ...items]);         // *** Save them
//         ^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− *** Use the callback form
}

(The primary fix there is to do [...abc, ...items] once. Although I do recommend using the callback, in many cases, just setAbc([...abc, ...items]); would work as well provided you don't memoize getCartItems and this is only done on mount or in response to a user click or similar.)

  • Related