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

161
Visualizações
State depending on other state not updating when child changes

I am trying to collect data to insert in database. I am using hooks states for this matter.

I have a products state:

const [product, setProduct] = useState(
      image: '',
      tags: [],
      available_colors: colors,
      available_sizes: talles,
   })

the available_colors depends on other state which is an array of colors. This array can be pushed with new elements and they are printed in the html. But the problem is, it is not updating in the products state.

Here is the colors state

   const [colors, setColors] = useState([
      { name: 'blue' },
      { name: 'green' },
      { name: 'red' },
   ])

I am updating it like this:

const setColorsAttr = async () => {
      const value = await Swal.fire({
         title: 'Nuevo Color',
         html: `
         <input type="text" id="talle-input" class="swal2-input"/>
      `,
         showCancelButton: true,
         focusConfirm: false,
         preConfirm: () => {
            const color = Swal.getPopup().querySelector("#talle-input").value
            return color
         }
      })

      if (value.isDismissed !== true) {
         setColors([
            ...colors,
            { name: value.value }
         ])
         setProduct({
           ...product,
           [product.available_colors]: colors
         })
      }
     
   }

But in the products isn't changing. I would appreciate your help! Thanks in advance!

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

0

setColorsAttr forms a closure over the current colors and setColors will update colors in the next render, so you can't use the latest colors right away.

You can use useEffect with colors as a dependency:

useEffect(() => {
  setProduct(previousProduct => ({...previousProduct, available_colors: colors}))
}, [colors])

setProduct in setColorsAttr can be removed

about 4 years ago · Juan Pablo Isaza Relatório

0

This happens because, setState works asynchronously, which means state doesn't update immediately.

To overcome this you need to update the product state in useEffect when color is updated.

useEffect(() => {   setProduct(previousProduct =>
({...previousProduct, available_colors: colors})) }, [colors])

To learn more about setState asynchronous working , checkout this . Why is setState in reactjs Async instead of Sync?

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