3

I want to load something from my API endpoint in componentDidMount, but that needs to have something else from the redux store passed into it.

Thing is, it seem that componentDidMount gets fired before the props are populated from redux, so the jwt auth token isn't in the redux state yet, and I get a 401 error.

How can I get the code to wait for the redux state to be loaded, then call the function, or have it loop every, lets say 500ms, until the props are identified?

If there's some place other than componentDidMount I should put it I'm open to suggestions.

cclloyd
  • 8,171
  • 16
  • 57
  • 104
  • So initially the token will be undefined so you can use componentDidMount and check whether token is not undefined and make an api call. componentDidMount(){if(this.props.auth != undefined) this.props.getDetails()} – Hemadri Dasari Aug 27 '18 at 10:54
  • Possible duplicate of [React Component wait for required props to render](https://stackoverflow.com/questions/37308719/react-component-wait-for-required-props-to-render) – Prasanna Aug 27 '18 at 14:02

2 Answers2

4

You make use of componentWillReceivePropslife cycle method which keeps track of incoming props.

componentWillReceiveProps(nextProps){
 if(this.props.auth.token !== nextProps.auth.token){
   //make a api call here
 }
}
CodeZombie
  • 2,027
  • 3
  • 16
  • 30
  • 2
    Fetching data in componentWillReceiveProps is not recommended. In fact using this lifecycle method is not recommended any more. – Peter Ambruzs Aug 27 '18 at 12:57
  • componentWillReceiveProps is deprecated, please see: https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops – Benjamin Heinke Apr 29 '20 at 15:50
1

You can wait for the auth token to get value. For example you can display a progress indicator until it gets a value. If it receives a value then you show your component with the componentDidMount.

render() {
   const {authToken} = this.props;
   return (
     <div> 
       {!authToken && ProgressIndicator}
       {authToken && ComponentWithApiFetch}
     </div> 
   )
}
Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36