1

In order to avoid .then(..) I'm using await. I'm calling a function which contains an Axios call, returned as response.data after an await. My functional component has a useEffect which is supposed to set an initial variable based on the result of this function.

My error is: Unexpected reserved word 'await' . It requires an async, but where do I put that in my invocation of the function?

const fetchUserInfo = async () => {

    const url = 'http://myapp.com/getUserInfo/';    
    
    const response = await axios.get(url);
    return response.data;
}

function App() {

  const [userInfo, setUserInfo] = useState({});

  // On initialization, fetch & set UserInfo
  useEffect(() => {    
      const result = await fetchUserInfo();   
      setUserInfo(result);
      alert('Completed useEffect init');
  }, []);

  return (..);
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    Maybe you can take a look at this answer: https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret – Ktoxcon Apr 16 '21 at 15:11

3 Answers3

3

Well you have few choices here:

  1. Get all logic inside the fetchUserInfo function and relocate fetchUserInfo function inside the App component so that it has access to state and can set the state. like this:

    function App() {
    
      const [userInfo, setUserInfo] = useState({});
    
      const fetchUserInfo = async () => {
          const url = 'http://myapp.com/getUserInfo/';
          const response = await axios.get(url);
          setUserInfo(response.data);
          alert('Completed useEffect init');
      }
    
      useEffect(() => {    
          fetchUserInfo();
      }, []);
    
      return (..);
    }
    
  2. You can define the function inside useEffect and call it there

    function App() {
    
      const [userInfo, setUserInfo] = useState({});
    
      useEffect(() => {
          const fetchUserInfo = async () => {
              const url = "https://jsonplaceholder.typicode.com/todos/1";
              const response = await axios.get(url);
              setUserInfo(response.data);
              alert("Completed useEffect init");
          };
    
        fetchUserInfo();
      }, []); 
    
      return (..);
    }
    
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
2

You can use IIFE function. I think it's best way to get your purpose

 useEffect(() => { 
   (async () => {
     const result = await fetchUserInfo();   
     setUserInfo(result);
     alert('Completed useEffect init');
   })() 
 }, []);
Egor Pashko
  • 354
  • 2
  • 8
1

You should call

const result = await fetchUserInfo(); 
setUserInfo(result);

In another function with async that you will call in the useEffect.

Or juste simply do it in the fetchUserInfo instead of returning the result