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!
resfrom yourgetProtectedAssetfunctiongetProtectedAsset->return resasyncand.then. If you are awaiting async function, skip thethenandcatchand just returnresin the same scope as you declare it. You are alreadycatching using atry/catchblock