Home > Back-end >  i am getting this errors while trying to show my information through the API
i am getting this errors while trying to show my information through the API

Time:12-13

enter image description here

And this is my code in react

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

function App() {
  const [listOfPosts, setListOfPosts] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:5000/api/regist").then((res) => {
      setListOfPosts(res.data);
    });
  }, []);
  return (
    <div className="App">
      {listOfPosts.map((value, key) => {
        return (
          <div className="post">
            <div className="title"> {value.email_U} </div>
            <div className="body">{value.nome_U}</div>
            <div className="footer">{value.pass}</div>
          </div>
        );
      })}
    </div>
  );
}

 
export default App;

I try to put it into an array but still says that .map is is not a function

CodePudding user response:

listOfPosts can be:

  1. null or undefined
  2. not an array

Make sure that:

  1. initialize listOfPosts like you did useState([])
  2. the api return an actual array and not null/undefined or other values (check res.data)

CodePudding user response:

You need to check that listOfPosts is not empty before you call map on it.

Something like:

  {listOfPosts?.length > 0 ? listOfPosts.map((value, key) => {
    return (
      <div className="post">
        <div className="title"> {value.email_U} </div>
        <div className="body">{value.nome_U}</div>
        <div className="footer">{value.pass}</div>
      </div>
    );
  })
  : null}

Since people in the comments seem to disagree with this approach, here is a working code sandbox. Except I replaced the return null with something that says ""Data loading..." and mocked an API request. Note that checking listOfPosts?.length > 0 implicitly filters out if he's returning undefined or null or some other ill-defined response. But yes, he should probably log the output of his API call to check that the data is what he expects.

  • Related