0

I'm calling my api inside componentDidMount and I want to set state to use the values later on, but I'm getting nulls. The API itself works, tested with postman, also calling other methods also works inside the componentDidMount.

    componentDidMount() {
        let url = window.location.pathname;
        let id = url.substring(url.lastIndexOf('/') + 1);
        console.log(id)
        userService.getDepartment(id).then(departments => this.setState({ ...departments }));
        console.log(this.state.address);
    }

This is what I see in the console log.

https://i.stack.imgur.com/aNF4l.png

My get function:

function getDepartment(id) {
    const requestOptions = { method: 'GET', headers: authHeader() };
    return fetch(`${config.apiUrl}/api/department/${id}`, requestOptions);
}

1 Answers1

0

The state won't update until AFTER the did mount. Can you try seeing if the result shows up inside a render()?

Edit: Didn't notice there wasn't a .catch() could you try adding that in and see what the console logs?

something like this:

//... rest of the component
componentDidMount() {
    let url = window.location.pathname;
    let id = url.substring(url.lastIndexOf('/') + 1);
    console.log(id)
    userService.getDepartment(id)
      .then(departments => this.setState({ ...departments }))
      .catch(err => console.log(err));
    console.log(this.state.address);
}
//... rest of the component
Michael Hoobler
  • 622
  • 5
  • 14
  • Tried it, still says null – Quelind Kajiura Apr 12 '21 at 19:35
  • @QuelindKajiura Hmm, is it possible to see what the `userService` code looks like? – Michael Hoobler Apr 12 '21 at 19:38
  • I edited my original post with the get method. – Quelind Kajiura Apr 12 '21 at 19:40
  • Thanks :). I made an edit to my post as well. Could try adding the `.catch(err => console.log(err));` and see what happens? – Michael Hoobler Apr 12 '21 at 19:43
  • No error was caught (nothing changed in the console log) – Quelind Kajiura Apr 12 '21 at 19:44
  • @QuelindKajiura Sorry, I'm stumped. I feel like the API route should be throwing a `sorry, couldn't fullfill your request` error, or a `404` or something. It seems like the API route thinks it's successfully fullfilling the request, but the "successful request" is a null value. I would try playing around with Postman and see what happens when you send a "bad request" (something you know is not going to work) to that route... but yea, time for debugging :( – Michael Hoobler Apr 12 '21 at 19:50