I'm new using reactjs. First case I want to get a json data from fetch url, but that json need async await to show all data. I managed to solve that problem, but now I want to append data from json to react return render. and then i get error like this Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.. This is my code
async function URL(url, id){
return fetch(url+"/"+id)
.then((response) => response.json())
.then((responseJson) => {
const myArrayresponse = responseJson.image.split("/");
return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
})
.catch((error) => {
return "images/icon.png";
});
}
const posts = datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
})
);
return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
<s.Container flex={1} jc={"center"} ai={"center"}>
{posts}
</s.Container>
</ResponsiveWrapper>
)
const post is [object Promise], how to append const post to react return render without [object Promise]?
You get [object Promise] is because you are actually returning an array of promise.
So in order to get it works, you can to use Promise.all which takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. Refer here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
You can do it this way:
const [posts,setPosts]= useState([])
async function URL(url, id){
return fetch(url+"/"+id)
.then((response) => response.json())
.then((responseJson) => {
const myArrayresponse = responseJson.image.split("/");
return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
})
.catch((error) => {
return "images/icon.png";
});
}
useEffect(()=>{
async function getPosts(){
const result = await Promise.all(datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
})
));
setPosts(result)
};
getPosts()
},[])
return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
<s.Container flex={1} jc={"center"} ai={"center"}>
{posts}
</s.Container>
</ResponsiveWrapper>
)