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 : {}
};
ponentDidMount(){
let temp = getUserPosts();
console.log(temp);
}
}
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 : {}
};
ponentDidMount(){
let temp = getUserPosts();
console.log(temp);
}
}
Share
Improve this question
edited Sep 16, 2019 at 2:58
Yilmaz
49.8k18 gold badges216 silver badges270 bronze badges
asked Jul 16, 2018 at 13:05
juxhin bletajuxhin bleta
3702 gold badges5 silver badges16 bronze badges
2
- "but in the other file" — What other file? Show us a minimal reproducible example. – Quentin Commented Jul 16, 2018 at 13:06
-
4
Odds are that
result.data
is simplyundefined
– Quentin Commented Jul 16, 2018 at 13:06
2 Answers
Reset to default 4getUserPosts
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 : {}
};
ponentDidMount(){
getUserPosts().then(temp => {
console.log(temp);
});
}
}
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 ponentDidMount
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:
ponentDidMount () {
let temp = await getUserPosts();
console.log(temp);
}