In my application, a token is used to retrieve user's data with a function. Here's it:
export function getUserInfos(token) {
if (token == "") {
window.location = "/";
}
axios.get(
url,
{
headers: {
"Authorization": "Bearer " + token
}
}
).then((result) => {
var surname = result.data.userInfos.surname;
var name = result.data.userInfos.name;
var userInfos = {
surname: surname,
name: name
}
document.title = "Profil - " + surname + " " + name;
console.log(userInfos)
return userInfos;
}).catch((err) => {
})
}
console.log(userInfos)
works fine when the function is called but impossible to get this value with setState()
, in the side of my component. Whatever I do I'm still getting undefined
. Here's the code in my component:
class HomePage extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
token: cookies.get('token')
}
};
componentDidMount() {
this.setState((state, props) => {
return {userInfos: getUserInfos(this.state.token)}
}, () => {
console.log(this.state.userInfos) // 'undefined'
})
}
render() {
console.log(this.state)
return (
<div>
<h1>MyHomePage</h1>
</div>
)
}
}
export default withCookies(HomePage);
I'm sure this is a problem with asynchronous functions but I can't surround where the problem is from or what I'm doing wrong. I also checked and this is not a problem with the importation of my function getUserInfos
.