I would like to set state variable books
as result of API. I cannot do it in componentDidMount
, because I don't have token at the beginning and need it to get result from API. Nothing happens with state books
when I run following code. If I put state.books=res.data
before return I got a result, but after manually refresh page.
constructor(props) {
super(props);
this.state = {
books: [],
};
}
and
static getDerivedStateFromProps(nextProps, state) {
if (nextProps.token){
axios.defaults.headers = {
"Content-Type": "application/json",
Authorization: "Token " + nextProps.token
}
axios.get('http://127.0.0.1:8000/api/book/own/')
.then(res => {
return {
books: res.data,
}
})
}
data from the API looks like:
{
id: 66,
isbn: "9780545010221",
title: "Title",
author: "Author,Author",
}
In the render method I call component with this.static.books
data.
Could you please advise me?