Reputation: 17
I have a Class-based React component. This is a child component and the state comes from another parent component. This is the JSX and it is inside a map function. Inside the map function, there is a big JSX code but I am putting only the relevant part.
{platformsList.map((item, index) => (
{item.platform_id ? (
<div>
{this.getSelectedProfiles(item.platform_id)}
</div>)) : ''}
The corresponding function is written above the render method. The response is an Object here:
getSelectedProfiles = async(id) => {
const token = Cookie.get('user-token');
const headers = {
'Content-Type': 'application/json',
authorization: token,
};
// Axios request
let response = await axios.get(`http://localhost:9999/profiles/${id}`, { headers: headers });
console.log(response);
return 'kkk';
}
The error message it is showing is: 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.
Since, this is a child component, I don't want to store in the state of React. I want to execute this component. Is there any way to do it without storing it in the state. I am new to React and don't know where I am doing wrong.
Upvotes: 0
Views: 137
Reputation: 83527
You need to await
on the result from the function call:
render () {
const getSelectedProfiles = async(id) => {
return 'kkk';
}
const selectedProfiles = await getSelectedProfiles(item.platform_id);
return {item.platform_id ? (
<div>
{selectedProfiles}
</div>) : ''}
However, this has the drawback that async
is blocking. If the async operation in getSelectedProfiles()
is long running (such as a network request), your render will hang. In that case, you must set the state of your component instead.
Upvotes: 0
Reputation: 11571
An async function returns a promise, it does not immediately execute and return a value (in this case 'kkk'
). There does not seem to be any reason getSelectedProfiles
is async either, so just remove that and make it synchronous.
getSelectedProfiles = (id) => {
return 'kkk';
}
Upvotes: 1