DEV Community

loading...

Discussion on: Fetching data with React Hooks

Collapse
mayuraitavadekar profile image
Mayur Aitavadekar • Edited

amazing post :) it really solved my problem.

here is what I wanted to do -
I was fetching the data from my backend method -

const [values, setValues] = useState({
    name: "",
    description: "",
    error: false,
    loading: false,
    success: false,
  });

const preload = (courseName) => {
    courseName = courseName.replace(/%20/g, " ");
    getCourseByName({ courseName }).then((data) => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } else {
        console.log("data retrieved : ", data);
        setValues({
          ...values,
          name: data.name,
          description: data.description,
          success: true,
        });
        console.log(values); // I was getting empty responses here
      }
    });
  };

  useEffect(() => {
    preload(match.params.courseName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

after that I just added this to use effect method -

  useEffect(() => {
    preload(match.params.courseName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [values.success]);

and I got my values printed right!

Summery : it will update the state of values only if value of success is changed :) but the problem here is that the values are getting printed 2 times.
Any thoughts?

Collapse
savagepixie profile image
SavagePixie Author

Just to make sure that I understand the problem. When you say that the values are being printed twice, you mean in the console, right? And, since you've got two console.logs, does that mean that it gets printed four times in total?

Collapse
mayuraitavadekar profile image
Mayur Aitavadekar • Edited

yes. console.log() print 4 times. Now below is detailed problem I had before doing comment on your post. see the useEffect.

first of all I wanted was to assign the fetched values to my state so that I can use it in my JSX of react component.
So I written following code :

const [values, setValues] = useState({
    name: "",
    description: "",
    error: false,
    loading: false,
    success: false,
  });

const preload = (courseName) => {
    courseName = courseName.replace(/%20/g, " ");
    getCourseByName({ courseName }).then((data) => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } else {
        console.log("data retrieved : ", data);
        setValues({
          ...values,
          name: data.name,
          description: data.description,
          success: true,
        });
        console.log(values); // use this values in react component
      }
    });
  };

  useEffect(() => {
    preload(match.params.courseName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // here I kept the brackets empty first.

So I wanted to assign the fetched data to my JSX elements in component. So I thought why not to check if it is printing correctly. here is what happened:
console.log("data retrieved : ", data); prints exact retrieved data. but console.log(values); this prints all empty values. So I thought the setValues() didn't work out.

After that I started to find out why my retrieved data is not assigned to setValues(). So I saw your post and I entered [values.success] in useEffect().

useEffect(() => {
    preload(match.params.courseName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [values.success]);

This correctly assigns fetched data into setValues and prints console.log(values); But problem here values gets printed two times. First with empty values and second with assigned values. This is mainly because useEffect method runs twice. first when DOM is mounted and second when value of success changed after fetching data from API. Hence I also didn't want this.

So I thought, lets keep this printing values aside. I did not print the
console.log(values) as I knew that it will be empty. I also didn't write console.log("data retrieved : ", data); as I knew that fetching works fine. What I did was, I kept the [ ] in useEffect() empty as before. I fetched data and assigned data values using setValues.

const [values, setValues] = useState({
    name: "",
    description: "",
    error: false,
    loading: false,
    success: false,
  });

const preload = (courseName) => {
    courseName = courseName.replace(/%20/g, " ");
    getCourseByName({ courseName }).then((data) => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } else {
        setValues({
          ...values,
          name: data.name,
          description: data.description,
          success: true,
        });
      }
    });
  };

  useEffect(() => {
    preload(match.params.courseName);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

After this, I directly used the values (values.name, value.description, value.loading, value.success) in my JSX and it worked fine and that was my end goal.

But I couldn't find solution to one question - why does console.log(values) prints empty values but in actuality the setValues works fine and assigns values and you can use those in your JSX.

PS: I know this comment has new level of verbosity ;)

Thread Thread
savagepixie profile image
SavagePixie Author

Thanks for such a detailed explanation! It is very helpful to understand what exactly you mean and to see what you've tried and why. Also, I'm glad you managed to get it to work as you wanted.

The reason why console.log() printed stuff twice is that useEffectwas running twice. Once when the page was first rendered (but before the data was fetched) and once on the re-render caused by retrieving the data. useEffect fires both on the first load of the page and on every state change (unless, obviously, you narrow it down in the dependency array). Since getCourseByName is an asynchronous operation, it will change the state after the page has loaded for the first time, thus triggering a re-render.