Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Why state is not storing data correctly?

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]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!