I am using Fetch API in componentWillReceiveProps, but i have some problems with asynchronous. I need to prevent re-render before I will get response from my Fetch request. Now everything is working but I render works 3 times.
-
can you please show some code on how you have it set up and why you are fetching in componentWillReceiveProps?Matt Aft– Matt Aft2017-03-30 16:20:15 +00:00Commented Mar 30, 2017 at 16:20
-
1Thanks, I am using redux, and I need call several dispatchs in componentWillReceiveProps. On of distatches call fetching data from server.Mag– Mag2017-03-30 16:24:58 +00:00Commented Mar 30, 2017 at 16:24
-
1so you're doing multiple dispatches which updates the state after each one and you want to wait until the last one completes before updating state and causing a re-render? You could use shouldComponentUpdate or maybe just create a new action to do all the requests then update the state just onceMatt Aft– Matt Aft2017-03-30 16:32:11 +00:00Commented Mar 30, 2017 at 16:32
-
@MattAft yes, you understood me right. I used shouldComponentUpdate but I thought that it's not right way, because I will put lot's of conditions for another parts of my component.Mag– Mag2017-03-30 16:38:29 +00:00Commented Mar 30, 2017 at 16:38
-
yeah that's why it might be easier to create an action that does all 3 API requests probably using Promise.all then update state just onceMatt Aft– Matt Aft2017-03-30 16:53:47 +00:00Commented Mar 30, 2017 at 16:53
1 Answer
Maintain a state variable for that, initially value of that variable will be false, once you get the response properly, change that variable to true. Use this variable to render the component.
Inside render:
render(){
if(this.state.dataFetched){
return (/*return component*/)
}else{
return <div>Loading....</div>
}
}
One more thing, instead of making network call in componentWillReceiveProps method, do that in componentDidMount lifecycle mthod.
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
6 Comments
componentDidMount to issue requests. Not sure why but I see so many questions where they try using componentWillReceiveProps instead.