Corbin Kristek
Corbin Kristek

Reputation: 39

rendering an array of objects from the axios response object

I am trying to render an array of objects inside the responce object im getting back from axios.

import React, { Component } from "react";
import axios from "axios";

class Bids extends Component {
  state = {
    adminPosts: [],
  };

  componentDidMount() {
    this.getPosts();
  }

  getPosts = async () => {

    let posts = await axios.get(
      "http://localhost:3001/api/posts/admin"
    );
    let allPosts = posts.data;

    this.setState({ adminPosts: allPosts });
  };


render() {
    let items = [...this.state.adminPosts];

/*
This is the item array from above
[
  {
    _id: 1,
    name: "john",
    posts: [
      { _id: 1000, price: "100" },
      { _id: 1001, price: "300" },
      { _id: 1002, price: "160" },
    ],
  },
  {
    _id: 2,
    name: "jack",
    posts: [{ _id: 1004, price: "400" }],
  },
  {
    _id: 3,
    name: "jill",
    posts: [],
  },
];

   */

    return (
      <div>
        <h1>hello from Sales</h1>

        {items.map((item) => (
          <li key={item._id}>
            <div className="container">
              <p> Name: {item.name}</p>
              <p> posts: {item.posts}</p> //React will not render this array of objects
            </div>
          </li>
        ))}
      </div>
    );
  }
}

export default Bids;

I dont get any errors with {item.name} in the render method but as soon as I put in {item.posts} I get this error Error: Objects are not valid as a React child (found: object with keys { _id, price}). If you meant to render a collection of children, use an array instead.

Upvotes: 0

Views: 3409

Answers (3)

Jason
Jason

Reputation: 443

If you want to render the whole array as text, you need to parse it and the answer from a-kon should do the work.

But if you want to render an element (example a div) per post, you need to use the map function too.

return (
      <div>
        <h1>hello from Sales</h1>

        {items.map((item) => (
          <li key={item._id}>
            <div className="container">
              <p> Name: {item.name}</p>
              <div> 
                <p>posts:</p>
                {item.posts.map((post) =>(<div>
                <span>id: {post._id} </span>
                <span>price: {post.price}</span>
                </div>))}
                </div>
            </div>
          </li>
        ))}
      </div>
    );

Upvotes: 2

Daniele Ricci
Daniele Ricci

Reputation: 15797

It seems you are already familiar with map, you can use it once again:

<p> posts: <ul>{item.posts.map(e => <li key={e._id}>price: {e.price}</li>)}</ul></p>

Upvotes: 1

a-kon
a-kon

Reputation: 131

You are trying to render an array posts here: <p> posts: {item.posts}</p> //React will not render this array of objects

You cannot render array of objects. But you can render JSON representation of it: <p> posts: {JSON.stringify(item.posts)}</p>

Upvotes: 0

Related Questions