murtaza52
murtaza52

Reputation: 47441

returning promise from useEffect

I was going through the article https://www.robinwieruch.de/react-hooks-fetch-data.

It gives the below 2 snippets to demonstrate how to deal with promises in useEffect. The first one throws an error while to second one doesnt.

first snippet -

  useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

second snippet -

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

Why does the second not throw an error, when fetchdata() is called it will return a promise, and thus a promise will be returned from useEffect too. How is the second snippet different from the first one ?

Upvotes: 2

Views: 5737

Answers (2)

Shivam Pal
Shivam Pal

Reputation: 123

You can only return nothing or a cleanup function for useEffect hook. The reason the first snippet is throwing an error is because you marked the function async and the functions that are marked async will always return a promise.

//The function is marked async
 useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

It breaks the rule of returning either nothing or a cleanup function.

However In the second snippet, you are using useEffect function to call an async function, but since the useEffect function itself is not async, that means it is not returning a promise

//this is not marked async
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

Upvotes: 3

Elmaz Feratovic
Elmaz Feratovic

Reputation: 76

From what l know you cant use promise directly on React Hook. You can use it inside in function and it will work. Hooks are there so that you do not need to use classes in React.

More about Hooks => https://reactjs.org/docs/hooks-overview.html

Upvotes: 0

Related Questions