Martin Olesen
Martin Olesen

Reputation: 41

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.

Upvotes: 1

Views: 144

Answers (1)

Houssam
Houssam

Reputation: 1877

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

Upvotes: 2

Related Questions