简体   繁体   中英

How to use useState hook to map JSON response from API

My API returns complex json like these.

[ 
 {id: 1, pub_date: "2021-01-06T20:24:57.547721Z"},
 {id: 2, pub_date: "2021-01-06T20:24:57.547721Z"},
 {id: 3, pub_date: "2021-01-06T20:24:57.547721Z"}
]

So my trial is like this

const [result, setResult] = useState({});
const [result, setResult] = useState(null);
const [result, setResult] = useState([]);

useEffect(() => {
  axios.get('http://localhost:8000/api/results/')
  .then(res=>{
    console.log(res.data); // correctly received
    setResult(res.data); // error
    console.log(result); // nothing appears
  })
  .catch(err=>{console.log(err);});
}, []);

However for any try, it shows the error like

Error: Objects are not valid as a React child (found: object with keys {id, pub_date} ). If you meant to render a collection of children, use an array instead.


I have some trial and errors.

There is still difficult behaiver to understand.

  const [cnt,setCnt] = useState(0);

  useEffect(() => {
    axios.get('http://localhost:8000/api/results/')
  
    .then((res)=> {
 
      setCnt(2);
      console.log(cnt);//shows 0

    })
    .catch(err=>{console.log(err);});
  }, []);

why setCnt is not workd?? I am more confused......

This error comes from your JSX render, where you're certainly trying to display directly your datas from API

useEffect(...)
...

return (
  <ul>
    { 
      result.map(r => (
          <li key={r.id}>{r.id} - {r.pub_date}</li>
      ))
    }
  </ul>
)

If you are calling setResult(res.data) , then your result state should be of type [] .

import React, { useEffect, useState } from "react";

const fetchData = () =>
  Promise.resolve({
    data: [
      { id: 1, pub_date: "2021-01-06T20:24:57.547721Z" },
      { id: 2, pub_date: "2021-01-06T20:24:57.547721Z" },
      { id: 3, pub_date: "2021-01-06T20:24:57.547721Z" }
    ]
  });

const ListItem = ({ id, pub_date }) => (
  <li>
    {id} &mdash; {pub_date}
  </li>
);

const ListItems = ({ items }) => (
  <ul>
    {items.map((props) => (
      <ListItem key={props.id} {...props} />
    ))}
  </ul>
);

const App = () => {
  const [result, setResult] = useState([]);

  useEffect(() => {
    fetchData().then((res) => {
      setResult(res.data);
    });
  }, []);

  return (
    <div className="App">
      <ListItems items={result} />
    </div>
  );
};

export default App;

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