简体   繁体   中英

Can't render Objects inside JSX. Throwing error Objects are not valid as a React child (found: [object Promise])

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 'value';
  }

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.

getSelectedProfiles is async and returns a promise which you are trying to render in your component. This is the reason react throws you the error.

You must not make API calls in render function. You can separate out this logic into another component and make the API call in componentDidMount lifecycle/useEffect hook depending on what type of component you write

{platformsList.map((item, index) => item.platform_id ? <Child key={index} id={item.platform_id} /> : null
}
...
const Child = ({id}) => {
   const [data, setData]  = useState({});
   const [isLoading, setLoading] = useState(true);
   useEffect(() => {
     const getSelectedProfiles = async(id) => {
        setLoading(true);
        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);
        setData({value: value}); // set the appropriate data here
        setLoading(false);
      }
   }, [id]);

   if(isLoading) return <div>Loading...</div>

   // return the appropriate content here from data. Do not render the object as it is 

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM