Console log data returned from axios in action

I have this action

export function registerUser(newUser, userList) {
    const req = axios.post(`/api/register`, newUser)
        .then(res => res.data);

    return {
        type: 'USER_REGISTER',
        registered: req.data.success,
        payload: [...userList, newUser]
    }
}

how to print the conentents of “req” ?

Before the return statement, could you just do console.log(req) and go from there?

I get req value as promise if I did this.

Hi @william1, rather than logging req itself you’ll have to log what req resolves to:

req.then(console.log)
1 Like

Thanks this worked. I get data like:

data: {
  success: true,
name: ssss
}

I wanted to return the success value so I tried

export function registerUser(newUser, userList) {
    const req = axios.post(`/api/register`, newUser)
        .then(res => res.data);

    return {
        type: 'USER_REGISTER',
        registered: req.success,
        payload: [...userList, req.user]
    }
}

But I get the registered value as undefined . Any ideas why is that ?

This is because req is a promise, and the promise itself doesn’t have a success property. Also note that by nature, promises are asynchronous – the promise may not resolve immediately but at some point in the future when you have already returned from the registerUser() function.

Thus, you have to return a promise chained to the request, and the registerUser() has to be consumed accordingly:

export function registerUser(newUser, userList) {
  return axios.post(`/api/register`, newUser)
    .then(res => res.data);
    .then(data => ({
      type: 'USER_REGISTER',
      registered: data.success,
      payload: [...userList, data.name]
    }))
}

registerUser('foo', ['bar', 'baz']).then(console.log)

– You can’t break out of promise land.

1 Like

I love you . This worked , I appreciate all the help.

Many thanks :revolving_hearts: :purple_heart: :blue_heart: :heart: :orange_heart: :yellow_heart: :green_heart:

1 Like

Anytime. :-)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.