developer
developer

Reputation: 229

injecting a url parameter into an an API call in react native

I'm passing some params from a page to the other to make an API call. What i've notice is when i hard code the value i'm suppose to get into the http call, i get the desired results but when i inject the value from the params into the call, if fails to work. so i thought the params wasn't able to pass till i did an alert in the render function and what i realized was the alert prompts twice, the first one is empty and the second prompt brings the value from the previous page, so then meaning in my componentDidMount, the call

state = {
  modalVisible: false,
  posts : [],
  itemID: ''
}

   componentDidMount = () => {
      const { navigation } = this.props;
      this.setState({itemID : navigation.getParam('itemID')})
      api.get('/items/'+`${this.state.itemID}`+'/test_items_details/'+`${userID}`+'/posts').then((response) => {
        let data = response.data.data
        this.setState({posts: data})
        console.log(JSON.stringify(this.state.posts))
      })
    }

Upvotes: 0

Views: 274

Answers (1)

Dan
Dan

Reputation: 8784

As per the docs, it states

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

Your code snippet is trying to access the state variable before it has in fact been updated.

You can do two things here:

  1. Simply use navigation.getParam('itemID') so now your URL becomes /items/${navigation.getParam('itemID')}/test_item_details/${userID}/posts.
  2. Use the setState callback, the snippet is added below.

Snippet:

this.setState({ itemID: navigation.getParam('itemID') }, () => {
  // this.state.itemID is now set, you can make your API call.
});

If your only intention to use this.state.itemID is for the URL, I would opt for the first option.

Upvotes: 1

Related Questions