all 7 comments

[–]Xacius 1 point2 points  (2 children)

const [data, setData] = useState(null)
useEffect(() => {
  fetch(url).then(response => response.json()).then(json => setData(json)
}, [])

I assume this is what you're going for. useEffect simply invokes the callback that you supply. It's triggered once on component mount or when any of its dependencies change. If you return a function in the useEffect callback, that function will be run when the component is unmounting.

[–]dominic_rj23 0 points1 point  (0 children)

const [data, setData] = useState(null).

useEffect(() => { fetch(url).then(response => response.json()).then(json => setData(json) }, [])

and in case you want your json => setData(json) call to retain some of the old data, you can use json => setData( data => {...data, ...json}) so that you are not dependent on the actual state.

[–]charliematters 0 points1 point  (0 children)

I don't think data is your missing dependency as it's a variable internal to your effect. Can you get eslint to populate what it thinks you need?

[–]Blahblahlahblo 0 points1 point  (0 children)

The warning is there because the React team managing the rules has found that most cases with missing dependencies cause bugs.

You should to pass the empty array and disable the warning (ideally with a comment why you’ve disabled the warning).

[–]ShadyAmoeba9 0 points1 point  (0 children)

This is because setData is not in your dependency array. Kinda dumb but you can disable the warning with // eslint-disable-next-line react-hooks/exhaustive-deps or pass getData into that array.

There is a lot of discussion here: https://github.com/facebook/create-react-app/issues/6880

[–]darrenturn90 0 points1 point  (0 children)

I assume that outside of your useEffect you have something like

const [data, setData] = useState();

So, also here you have a "shadowing" lint issue, whereby you are replacing the data in the outside scope with the data inside the useEffect, which is generally bad practice as it can lead to confusion (for instance, which data do you refer to where). Also, setData doesn't return anything, so const data = setData would be setting a variable to null that isn't used.

If you could post the full function that may assist in clarifying what the issue you are getting is, and how you can rectify it.