最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to map over a JSON response in React - Stack Overflow

programmeradmin1浏览0评论

Hi I'm trying to learn how to use React with an API response. I have a GraphQL API endpoint that is returning information on products in JSON. I would like to loop over the response and render a react ponent for each product simply displaying the product name.

The JSON response looks like this:

{
  "data": {
    "products": [
      {
        "productName": "Pepsi",
        "price": "1.99",
      },
      {
        "productName": "Coke",
        "price": "2.99",
      },
      // and so on...
    ]
  }
}  

I've successfully console logged each product name by doing the following (I'm using axios):

async function contactAPI() {
  return await axios({
    url: '',
    method: 'post',
    data: {
      query: `
        QUERY GOES HERE
          `
    }
  })
}

async function goFetch() {
  let resp = await contactAPI();
  for (let entry in resp.data.data.products) {
    console.log(resp.data.data.products[entry]['productName']);
  }  
}

But now I would like to render a react ponent for each product, but I keep getting the error Objects are not valid as a React child (found: [object Promise]). Below is the code I'm using right now. How can I fix this so that I can return a react ponent for each product with the product name?

App.js

async function contactAPI() {
  return await axios({
    url: '',
    method: 'post',
    data: {
      query: `
        QUERY GOES HERE
          `
    }
  })
}

async function App() {
  let resp = await contactAPI();
  return (
    <div>
      {resp.map(p => (
        <div>
          <ProductCard productName={p.productName} />
        </div>
      ))}
    </div>
  );
}

ProductCard.js

function ProductCard(props) {
  return (
    <div>
      <div>{props.productName}</div>      
    </div>
  );
}

Edit: Based on Andy's suggestion, I tried using states and useEffect, but I'm getting two errors. The first one is Error: Objects are not valid as a React child (found: [object Promise]). and the second one is Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function ponent. The second error points to const [products, setProducts] = useState([]);

This is my current code:

async function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function getData() {
      const res = await contactAPI();
      setProducts(res.data.data.products);
    }
    getData();
  }, []);

  return (
    <div>
      <div>
        {products.map(p => (
          <div>
            <ProductCard productName={p.productName} />
          </div>
        ))}
      </div>
    </div>
  );
}

Edit 2: Fixed by removing the async keyword from the original function App()

Hi I'm trying to learn how to use React with an API response. I have a GraphQL API endpoint that is returning information on products in JSON. I would like to loop over the response and render a react ponent for each product simply displaying the product name.

The JSON response looks like this:

{
  "data": {
    "products": [
      {
        "productName": "Pepsi",
        "price": "1.99",
      },
      {
        "productName": "Coke",
        "price": "2.99",
      },
      // and so on...
    ]
  }
}  

I've successfully console logged each product name by doing the following (I'm using axios):

async function contactAPI() {
  return await axios({
    url: 'https://graphqlexample./api/products',
    method: 'post',
    data: {
      query: `
        QUERY GOES HERE
          `
    }
  })
}

async function goFetch() {
  let resp = await contactAPI();
  for (let entry in resp.data.data.products) {
    console.log(resp.data.data.products[entry]['productName']);
  }  
}

But now I would like to render a react ponent for each product, but I keep getting the error Objects are not valid as a React child (found: [object Promise]). Below is the code I'm using right now. How can I fix this so that I can return a react ponent for each product with the product name?

App.js

async function contactAPI() {
  return await axios({
    url: 'https://graphqlexample./api/products',
    method: 'post',
    data: {
      query: `
        QUERY GOES HERE
          `
    }
  })
}

async function App() {
  let resp = await contactAPI();
  return (
    <div>
      {resp.map(p => (
        <div>
          <ProductCard productName={p.productName} />
        </div>
      ))}
    </div>
  );
}

ProductCard.js

function ProductCard(props) {
  return (
    <div>
      <div>{props.productName}</div>      
    </div>
  );
}

Edit: Based on Andy's suggestion, I tried using states and useEffect, but I'm getting two errors. The first one is Error: Objects are not valid as a React child (found: [object Promise]). and the second one is Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function ponent. The second error points to const [products, setProducts] = useState([]);

This is my current code:

async function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function getData() {
      const res = await contactAPI();
      setProducts(res.data.data.products);
    }
    getData();
  }, []);

  return (
    <div>
      <div>
        {products.map(p => (
          <div>
            <ProductCard productName={p.productName} />
          </div>
        ))}
      </div>
    </div>
  );
}

Edit 2: Fixed by removing the async keyword from the original function App()

Share Improve this question edited Oct 30, 2021 at 10:42 bourne2077 asked Oct 30, 2021 at 8:32 bourne2077bourne2077 1811 gold badge6 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Since you're using functional ponents you should implement hooks to 1) get the data, and 2) manage the ponent state. useEffect to get the data on first render, and useState to store and manage the data that's returned. You can then map over that data stored in the state to create the JSX.

const { useEffect, useState } = React;

function App() {

  // Initialise the state with an empty array
  const [products, setProducts] = useState([]);
  
  // Call `useEffect` with an empty dependency array
  // which will ensure it runs only once
  useEffect(() => {

    // Call the contactAPI function, wait for
    // the data and then update the state with the
    // product array
    async function getData() {
      const res = await contactAPI();
      setProducts(res.data.data.products);
    }
    getData();
  }, []);

  // If the state array is empty show a simple message
  if (!data.length) return <div>No data</div>;

  // Otherwise `map` over the state and produce the JSX
  return (
    <div>
      {products.map(product => (
        <div>
          <ProductCard productName={product.productName} />
        </div>
      ))}
    </div>
  );
}

To display the JSON data in React i have used 2 methods. 1.You can make use of class ponent for fetch it as api. 2.You can import the JSON data file and simply map it.

This is my way of displaying JSON data on React applicatons.

发布评论

评论列表(0)

  1. 暂无评论