I am, for the most part, following this tutorial.
My Django API's set up well. I have this service function:
export default class GoalService{
getGoals() {
const url = `${API_URL}/api/goals`;
return axios.get(url).then(response => response.data);
}
}
Which is called by the componentDidMount
method in my GoalList
:
class GoalTable extends Component {
constructor(props) {
super(props);
this.state = {
goals: [],
now: now.getDate(),
}
}
componentDidMount() {
var self = this;
goalService.getGoals().then(function (result) {
console.log(result);
self.setState({ goals: result.data })
});
}
render() { ... }
(This is step 8 of the above-linked tutorial).
Now, when I try to use { this.state.goals.map(...) }
, I get the error TypeError: this.state.goals is undefined
. Looking at other threads, a lot of people seem to have had this problem—but it comes about because they've used setState()
outside of the request being made and, since setState()
is asynchronous, the state is set to something blank. I'm using it inside of a call to then
, so I don't think that's the issue.
I tried adding a second argument to then
(in case this operation wasn't successful), but, the getGoals()
call is successful, and successfully prints out the JSON sent back by Django's API. Similarly, I can see that the request went as expected in the Network tab of the developer tools.
What could be going wrong here? Why isn't the state properly updating w/ the returned JSON?
result.data
isn'tundefined
? All you've done above is logresult
itself, i can't be sure that result is an object or if it's json, or if it even has a data property.this.state.goals
is becomingundefined
after you've already initialized it in the constructor, then you must be setting it to that. In other words - it looks likeresult.data
is undefined. I notice that you're doing.data
in both your service and your component - are you accidentally effectively doingresponse.data.data
?response.data.data
.