0

I am new to reactJS , my problem is that I want to assign my varaiable a value that has been returned from a axios function.When I do this, I get undefined value for u1.

 function getUsername(userid){
        var user = ''
        axios.post('/api/getuserdata' , {_id:userid}).then(res=>{
            console.log(res.data)
            const userdata = res.data[0]
            user = userdata.username

        }).catch(err=>{
            console.log(err)
        })

        return user

    }
    const u1 = getUsername(id)
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Ramesh Reddy Aug 22 '21 at 12:23

2 Answers2

0
async function getUsername(userid) {
    try {
        const result = await axios.post('/api/getuserdata' , {_id:userid});
        const user = result.data;
    }
    catch (error) {
        console.log(error)
    }
}
Amr Eraky
  • 1,423
  • 7
  • 13
0

The reason your code doesn't work is that the POST request handled by axios is async, your getUsername function won't wait for that request to resolve and return user immediately after it's called. The simplest solution is that make your getUsername async and call it in another async function, or if you want to use the result returned from POST request for some other stuff, you can store it as state in React, it would be better. You can use something like this:

const getUsername = async (userid) => {
    try {
        const response = await axios.post("/api/getuserdata", { _id: userid });
        const userdata = response?.data?.[0]?.username || "";
        return userdata;
    } catch (error) {
        console.log(`error`, error);
    }
};

// in another function
const doSomethingWithUsername = async (id) => {
    const username = await getUsername(id);
    // other stuff..
}