I'm taking my first steps with react and I'm trying to make a get request with data that I get in app i pass it to other component. The problem is that i get this:
[undefined, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise]
What is wrong?
Here is my code:
APP.JS
const elements1 = await axios.get(axios.defaults.baseURL)
// this works ok.
const Allelements = await Promise.all(elements1.data.elements.map(element => {
if(element.type == 'CONTENT'){
const contentType = responseElements.data.elements.map(element => element)
this.setState({content : contentType})
}
}))
HERE I SEND THE STATE to home:
<Route path="/" exact render={(props) => <Home {...props} content={this.state.content} />}/> // this send the data ok.
HOME receives IT and pass it, and work ok:
<ContentGroupTall content={this.props.content}>
CONTENTGROUPTALL.JS --> HERE is the problem.
componentDidUpdate(){
const a = this.props.content // a have the data
const b = a.map(element => element.content).filter(element => element != null)
const c = b.map(element => {
if(element.type == 'RAIL'){
return axios.get(`http://url:3000/${element.id}`)
}
})
console.log('cccccccc', c) --> [undefined, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise]
axios.get
returns a Promise, so you map an array to promises, except the first case, when element.type
probably doesn't equal RAIL
.
You can filter them out first, then resolve it with Promise.all
:
Promise.all(
b.filter(element => element.type === 'RAIL')
.map(element => axios.get(`http://url:3000/${element.id}`))
)
.then(res => res.forEach(element => console.log(element)));
You can also use destructuring to avoid verbosity:
Promise.all(
b.filter(({type}) => type === 'RAIL')
.map(({id}) => axios.get(`http://url:3000/${id}`))
)
.then(res => res.forEach(element => console.log(element)));
Wrap your c array with Promise.all. Then you can continue with the resolved promises in a then statement after Promise.all to get the values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.