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

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

reactjs - how can I use async data from node api?

I'm fetching data from node.js. So it's kinda late to get data... I guess that's why my console says 'null' all the time :/ I tried several way to fix it, but it didn't help at all.

I did use UseState but it ended up saying 'null' data. My page kept saying

TypeError: Cannot read property 'map' of null

here's my react code:


const Start = () => {
  const [isLoading, setIsLoading] = useState(false);

  const dataList = null;

  useEffect(() => {
    const getData = async () => {
      setIsLoading(true);
      await axios
        .post('/api/getData')
        .then((res) => {
          console.log(res.data.result);
          // ?? at this point, this console.log says what I exactly want.
          return (dataList = res.data.result);
        })
        .catch((err) => console.log(err));
      setIsLoading(false);
    };

    getData();
  }, []);

  if (isLoading) return <div>...Loading...</div>;

  return (
    <div>
      ??????
      {dataList.map((item, idx) => (
        <p>{item[0].dataName}</p>
      ))}
      ????
    </div>
  );
};

What should I do to use my data which was fetched from node.js? the data is long, large JSON.

question from:https://stackoverflow.com/questions/65893407/how-can-i-use-async-data-from-node-api

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

1 Answer

0 votes
by (71.8m points)

To properly use React, you should keep data inside the state, so React's virtual DOM can properly render items according to that data (for your case).

Also, no need to chain .then whilst using await.

On another note, it is weird that you are using axios.post instead of axios.get for fetching the data, just a piece of friendly advice.

The reason why your const dataList = null never gets updated is because you are initializing it inside the render function, meaning every time the state gets updated (setIsLoading) your dataList gets reinitialized to null

const Start = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [dataList, setDataList] = useState([]);

  useEffect(() => {
    const getData = async () => {
      setIsLoading(true);

      const response = await axios.post('/api/getData');

      setIsLoading(false);
      setDataList(response.data.result);
    };

    getData();
  }, []);

  if (isLoading) {
    return <div>...Loading...</div>;
  }

  return (
    <div>
      {dataList.map((item, idx) => (
        <p>{item[0].dataName}</p>
      ))}
    </div>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...