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

139
Visualizações
Trying to manipulate state array in React

I need to write two functions, one for update shopping cart with new products (reserves) and another one to remove products from cart. I have many product suppliers, so i want to divide my "cart" array into sections like this:

[
"supplier1": ["product0": {props}, "product1": {props}, "productN": {props}],
"supplier2": ["product0": {props}, "product1": {props}, "productN": {props}],
"supplierN": ["product0": {props}, "product1": {props}, "productN": {props}],
]

I can succesfully add suppliers to my state array and also pushing product to supplier's arrays.
When i use

setCart(cart)

cart array is updating but this is still old array, so React won't rerender my component

And in this case

setCart([...cart])

cart array just becomes empty
So here is code of adding new products

const [cart, setCart] = useState([])
const addToCart = useCallback((options) => {
  //options.cart_section and options.reserve
  if(typeof cart[options.cart_section] === 'undefined'){
    cart[options.cart_section] = []
  }
  cart[options.cart_section].push(options.reserve)
  setCart([...cart])
}, [])

and code of removing products form cart

const removeFromCart = useCallback((options) => {
  let index = cart[options.cart_section].indexOf(options.reserve) - 1
  cart[options.cart_section].splice(index,1)
  setCart([...cart])
})

It removes specified product but React doesn't rerender component (same as in function below)
Sorry for my english and thanks for help

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  • Fist point. You can not assign key value like you did to array. but you can push objects as items of array. each object considered as a unique supplier. So your array should be like this:
[
  {
    supplierName: 'supplie name 1',
    products: [
     {name: 'product name 1'}, 
     {name: 'product name 2'}
    ]
  },
  {
    supplierName: 'supplie name 2',
    products: [
     {name: 'product name 1'}, 
    {name: 'product name 2'}]
  }
]
  • Second point. never mutate state itself. you are mutating cart by pushing some thing inside of it. This way react will not rerender your component as you are not updating your state via setState. you have to create a variable in your function from your state this way:
  let tempCart = cart.map(object => ({...object}))

after that you can push new supplier or product and at the end you should update your state via setCart. this way:

  setCart(tempCart)

this way you are updating your state via setState and react will treat this action as (need DOM to update) then your component will get rerender

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