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

202
Visualizações
setState does not trigger render after item deleted from object

In my app you can set an age restriction on a link. If there is an age restriction on the link will it have an item named ageRestriction in the link state which contains an int which is the age. If it does not have an age restriction there will be none.

When i chance rather or not the link has an age restriction the follow code runs:

useEffect(async () => {
        if(ageRestriction === false) {
            const newLink = link;
            delete newLink.ageRestriction
            setLink(newLink)
        }
        else if(ageRestriction === true) setLink({...link, ageRestriction: storedAge})
    }, [ageRestriction])

which should then trigger the following code:

useEffect(() => {
        const validate = validateLink(link)
        if(validate) {
            setError(validate)
        }

        setError({})
        dispatch({type: 'update', link: link, index: index})
    }, [link])

If I add an age restriction in the first piece of code the useEffect in the second piece of code trigger. If I delete the ageRestriction item from the object and set the state the useEffect in the second piece of code does not trigger. What can I do to fix this thanks! in advance.

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

0

The dependency of your second useEffect should be link.ageRestriction because the comparison between objects is done by reference, thus removing the property from the link object doesn't trigger the effect:

useEffect(() => {
  const validate = validateLink(link)
  if(validate) {
    setError(validate)
  }

  setError({})
  dispatch({type: 'update', link: link, index: index})
}, [link.ageRestriction])

Alternatively, you can create a new object when removing the property in the first useEffect as follow:

useEffect(async () => {
  if(ageRestriction === false) {
    const newLink = link;
    delete newLink.ageRestriction
    setLink({ ...newLink })
  }
  else if(ageRestriction === true) setLink({...link, ageRestriction: storedAge})
}, [ageRestriction])
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