2021年4月8日星期四

React: String automatically converted to [object promise] when called from another component

I'm developing the front-end for my spring boot application. I set up an initial call wrapped in a useEffect() React.js function:

useEffect(() => {      const getData = async () => {          try {            const { data } = await fetchContext.authAxios.get(              '/myapi/' + auth.authState.id            );            setData(data);          } catch (err) {              console.log(err);          }      };      getData();      }, [fetchContext]);  

The data returned isn't comprehensive, and needs further call to retrieve other piece of information, for example this initial call return an employee id, but if I want to retrieve his name and display it I need a sub-sequential call, and here I'm experiencing tons of issues:

    const getEmployeeName = async id => {          try {            const name = await fetchContext.authAxios.get(              '/employeeName/' + id            );              console.log((name["data"]));  // <= Correctly display the name            return name["data"];          // return an [Object promise],           } catch (err) {              console.log(err);          }      };  

I tried to wrap the return call inside a Promise.resolve() function, but didn't solve the problem. Upon reading to similar questions here on stackoverflow, most of the answers suggested to create a callback function or use the await keyword (as I've done), but unfortunately didn't solve the issue. I admit that this may not be the most elegant way to do it, as I'm still learning JS/React I'm open to suggestions on how to improve the api calls.

var output = Object.values(data).map((index) =>  <Appointment    key={index["storeID"].toString()}    // other irrelevant props    employee={name}     approved={index["approved"]}  />);  return output;  
https://stackoverflow.com/questions/67013485/react-string-automatically-converted-to-object-promise-when-called-from-anoth April 09, 2021 at 08:23AM

没有评论:

发表评论