Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally render useEffect fetch React

Making a video game clip posting app. I have a controller on the backend that will give me the clips in order of most commented on clips to least. I would like to switch between having the data ordered normally, to from most to least comments by using a select tag (later I will add more filters). I was hoping I could conditionally render both of the fetches based on a state from the select tag onChange, but I got an error.

 Line 18:5:  React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks
  Line 24:5:  React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks

this is my code. Note that I was just testing it with a boolean.

 const boolean = true;
  if (boolean == true) {
    useEffect(() => {
      fetch("/clips")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    }, []);
  } else {
    useEffect(() => {
      fetch("/most_comments")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    }, []);
  }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the error says, you can’t have useEffect called conditionally. Instead, call it a single time regardless, and inside that function, look to see whether you need to fetch the clips or the comments.

useEffect(() => {
    if (boolean) {
        fetch("/clips")
            .then((r) => r.json())
            .then((data) => setClipData(data));
            // don't forget to .catch errors here
    } else {
        fetch("/most_comments")
            .then((r) => r.json())
            .then((data) => setClipData(data)); // did you mean to call setCommentsData or something here?
            // don't forget to .catch errors here
    }
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading