Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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......


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
533 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...