1

I am trying to render the response from Axios in reactjs. The response is data from the MySQL database. Please see my code below and am getting the error message 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. I will appreciate any assistance. Thanks.

const Products = () => {

  const fd =  () => {
    return Axios.get("http://localhost:5000/popular-products")
           .then(response => response.data)
  }

  return (
    <Container>
      {fd().then((data) => {
        data.map((item)=>(
          <h1>{item.prod_name}</h1>
        ))
      })}

    </Container>
  );
};

export default Products;
6
  • 1
    you're trying to resolve the promise WITHIN JSX. do everything within that function (fd) and get the final data. use useState and set the state with that final data and THEN you map over the list and return JSX. Commented Dec 28, 2021 at 0:30
  • 1
    Does this answer your question? How can display data fetched from an api properly in react? Commented Dec 28, 2021 at 0:32
  • I tried useState, but the axios response is loading multiple times Commented Dec 28, 2021 at 0:33
  • what do you mean by 'loading multiple times' ? Commented Dec 28, 2021 at 0:35
  • @MattU Yes it answers my question. Thanks for your help. Commented Dec 28, 2021 at 0:43

1 Answer 1

3

Best practice to resolve promise outside the JSX. You can use bellow approach if you like.

const [items, setItems] = useState([]);

const fetch = () => {
    axios
      .get("http://localhost:5000/popular-products")
      .then((response) => setItems(response.data));
};

// component did mount
useEffect(() => {
   fetch();
}, []);

return (
  <div className="App">
      {items.length > 0 && items.map((item) => <p key={item.id}>{item.prod_name}</p>)}
  </div>
);

In here I have used component did mount to fetch data when component mounted.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.