'React js cannot return data from function

I have two functions, one is a page that calls for data from a function that gets data to and from a server.

The function that gets data to and from a server:

import React, { useEffect, useState, createRef, lazy, useContext } from "react";
import { UserContext } from "./UserContext";

import jwt_decode from "jwt-decode";

import axios from "axios";

export async function getProtectedAsset(url, user, setUser) {
  try {
    const res = await axios
      .post(url, token)
      .then((res) => {
        console.log(res.data);
        return res.data;
      })
      .catch((err) => {
        console.error(err);
      });
  } catch (error) {
    console.log(error);
    throw err;
  }
}

The code that calls this function:

useEffect(async () => {
    try {
      let res = await getProtectedAsset(
        "http://127.0.0.1:5002/mypage",
        user,
        setUser
      );

      console.log(res);
      
    } catch (error) {
      console.error(error.message);
    }
  }, []);

getProtectedAsset will do a successful console.log(res.data); with the data from the server. The calling function that uses useEffect when doing console.log(res); will write undefined to the console.

Why can't I simply return from the function? Obviously the data is received from the server, but for some reason a function cannot return it? I am very confused

Thank you for your help!



Solution 1:[1]

You should not use async in useEffect. This is not supported.

I am not sure why you can't use getProtectedAsse(...).then(res=> {}).

But if you want to run getProtectedAsse() synchronously, try like the following instead.

useEffect(() => {
    const asyncInternalFunc = async () => {
      try {
        let res = await getProtectedAsset(
          "http://127.0.0.1:5002/mypage",
          user,
          setUser
        );
        console.log(res);
        return res;
      } catch (error) {
        console.error(error.message);
      }
    }
    asyncInternalFunc().then();
  }, []);

Updated async function to return the response.

export async function getProtectedAsset(url, user, setUser) {
  try {
    const res = await axios.post(url, token);
    return res;
  } catch (error) {
    console.log(error);
    throw err;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1