juxhin bleta
juxhin bleta

Reputation: 370

Return results from Axios

This is my code in js with which I am trying to request something from api and then return the result or error, but in the other file when I try to log this I get "Undefined" value. What am i missing here?

import {baseAPI} from "../core/globals";
import axios from "axios/index";

export const getUserPosts = () => {
    return(
        axios({
            method : 'get',
            url: baseAPI+'post',
            headers:{
                Authorization : localStorage.getItem('token')
            }}
        ).then((result) => {
            return result.data
        }).catch((error) => {
            return error;
        })
    );
}

The other file looks like this

import { getUserPosts } from '../actions/userProfile';
import {baseAPI} from "../core/globals";

export default class Profile extends React.Component{

    state = {
        postResult : {}
    };
    componentDidMount(){
        let temp = getUserPosts();
        console.log(temp);
    }
}

Upvotes: 2

Views: 10461

Answers (2)

AJC24
AJC24

Reputation: 3336

The issue you have is that axios returns a Promise and you are not waiting for your Promise to be resolved. Therefore the value returned from your axios method is undefined in your console log.

What you should use in your componentDidMount method is:

getUserPosts()
.then((temp) => {
  console.log(temp);
});

Update: An alternative, if you're using Node v7.6.0 or greater is to take advantage of the async and await keywords to ask your code to wait for the promise to be resolved.

So you could also use:

componentDidMount () {
  let temp = await getUserPosts();
  console.log(temp);
}

Upvotes: 3

Tholle
Tholle

Reputation: 112777

getUserPosts returns a promise, so you need to make sure it is fulfilled before you do anything with the result.

Example

export default class Profile extends React.Component{
    state = {
        postResult : {}
    };
    componentDidMount(){
        getUserPosts().then(temp => {
            console.log(temp);
        });
    }
}

Upvotes: 4

Related Questions