Hi, please i'm stuck.
is somebody knows how to make many request in a react component or route?
componentDidMount = () => {
const { match: { params } } = this.props
fetch(`/w/${params.work}`)
.then(res => res.json())
.then(work => this.setState({ work }))
fetch('/works')
.then(res => res.json())
.then(otherWorks => this.setState({ otherWorks }))
}
something like this that works.
I'm a beginner with React so i don't really want things like Redux
i just want a beginner way.The first fetch work but not the second
Oldest comments (8)
I think promise.all() is going to be what you're looking for.
Okay! i try it
Your code is making two requests at once - what isn't working about it exactly?
i'm supposed to receive an array of data in the otherWorks but i got an empty array
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.Guys i'm sorry.It was a
{}
I'd forgotten somewhere really sorry.And thanks for your answers i think it'll save my life in few days
if you have multiple callback asynchrous update the setState, you should consider this method to make sure they don't overwrite each other or race conditions:
Use axios, install axios. And use axios to fetch api in react.
I am using axios in my project.