Maybe it's not about the requests, but how you expect to use the responses. The React.Component's setState method is asynchronous, so you can't expect the component's state to have both work and otherWorks every time render() is called.
As Leighton suggested, Promise.all would help you make only one setState call, but it still doesn't cover the case right after mounting the component when neither of the values are present in the state.
Maybe consider adding a loading flag in the state that is set to false when both requests have completed, so render() can show a loading animation while the requests are still waiting for responses.
classMyCompextendsReact.Component{constructor(props){super(props);this.state={loading:true,work:undefined,otherWorks:undefined};}componentDidMount=()=>{const{match:{params}}=this.propsconstfetchWork=fetch(`/w/${params.work}`)constfetchOtherWorks=fetch('/works')Promise.all([fetchWork,fetchOtherWorks]).then(([work,otherWorks])=>{this.setState({loading:false,work,otherWorks});}).catch(error=>{// handle errors})}render(){const{loading,work,otherWorks}=this.state;if(loading){return<div>Stillloading!</div>
}else{return(// whatever you want to do with `work` and `otherWorks`);}}}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Maybe it's not about the requests, but how you expect to use the responses. The
React.Component
'ssetState
method is asynchronous, so you can't expect the component's state to have bothwork
andotherWorks
every timerender()
is called.As Leighton suggested,
Promise.all
would help you make only one setState call, but it still doesn't cover the case right after mounting the component when neither of the values are present in the state.Maybe consider adding a
loading
flag in the state that is set tofalse
when both requests have completed, sorender()
can show a loading animation while the requests are still waiting for responses.