Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda