0

I'm getting the error "React Hook React.useEffect has a missing dependency: 'openPosts'" where openPosts is state in a Hook.

export const Posts = (props) => {

  const [openPosts, setOpenPosts] = React.useState([]); *openPosts is an array of numbers*

  React.useEffect(_ => {
    let filteredOpenPosts = openPosts.filter(num => num >= 1);
    setOpenPosts(filteredOpenPosts);
  }, [props.userId]);

I've read around but I haven't understood why I'm getting this error. Can I ignore it?

I essentially want state to filter as above with a change in props.userId and thought this would be a clean way to do it. I could also create more state to track any change in props.userId but if the above can work I'd prefer it.

3
  • What is the likelyhood of openPosts changing if/when userId changes? By not including openPosts as a dependency of useEffect it simply means that if openPosts changes then your useEffect code won't re-run unless userId is also updated. Commented Sep 17, 2019 at 11:40
  • openPosts is updated each time userId changes. The behaviour you described is intentional. Commented Sep 17, 2019 at 11:47
  • Hi mista, check my solution and let me know if that helps. Commented Sep 17, 2019 at 11:53

1 Answer 1

5

If you don't want to specify the dependency, then you can try this,

React.useEffect(_ => {
    setOpenPosts(prevState => prevState.filter(num => num >= 1));
}, [props.userId]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.