I'm learning reactjs. I want to get result from fuction findTenloaidv(id) when load list bpdvList but error
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json();
this.setState({
bpdvs: bangphi,
isLoading: false,
})
}
async findTenloaidv(id){
const loaidv = await (await fetch(`/gvnhanh/loaidv/${id}`)).json();
return loaidv.tenloai
}
render(){
const {bpdvs, isLoading} = this.state;
const bpdvList = bpdvs.map(bpdv =>{
return <tr key={bpdv.idbpdv}>
<td className="text-center">{bpdv.iddv}</td>
<td className="text-center">{this.findTenloaidv(bpdv.idloaidv)}</td>
<td className="text-center">{bpdv.tendv}</td>
<td className="text-center">{bpdv.mota}</td>
<td className="text-center">{this.currencyFormat(bpdv.gia)}</td>
<td className="text-center">{bpdv.donvitinh}</td>
</tr>
});
}
There are a couple errors here.
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json(); // Here
const bangphi = await fetch('Your endpoint') //await your fetch data
const data = await bangphi.json() // Then convert to json
this.setState({
bpdvs: data.bangphi, // changed here
isLoading: false,
})
}
// Change this to match
async findTenloaidv(id){
const loaidv = await (await fetch(`/gvnhanh/loaidv/${id}`)).json();
return loaidv.tenloai
}
The problem is here
<td className="text-center">{this.findTenloaidv(bpdv.idloaidv)}</td>
findTenloaidv
method returns a promise
as it is async
which is type of object ([object Promise])
. That's why react throws this error Objects are not valid as a React child
.
You need to map the currency format while you're fetching data. Try like this
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json(); // Here
const bangphi = await fetch('Your endpoint') //await your fetch data
const data = await bangphi.json() // Then convert to json
const bpdvs = data.bangphi.map(async bpdv => {
const loaidv = await this.findTenloaidv(bpdv.idloaidv)
return {
...bpdv,
idloaidv: loaidv.tenloai
}
})
this.setState({
bpdvs,
isLoading: false,
})
}
...
<td className="text-center">{bpdv.iddv}</td>
<td className="text-center">{bpdv.idloaidv}</td>
....
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.