cclloyd
cclloyd

Reputation: 9205

Wait for redux props in componentDidMount

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.

Upvotes: 3

Views: 3657

Answers (2)

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

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> 
   )
}

Upvotes: 1

CodeZombie
CodeZombie

Reputation: 2087

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
 }
}

Upvotes: 4

Related Questions