简体   繁体   中英

Cannot read property 'map' of undefined" Error in React

I have this code here. I keep getting an error: Cannot convert undefined or null to object (or sometimes TypeError: Cannot read property 'map' of undefined.)

Here is my code

const AdresList = (props) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    getXAddress()
      .then((response) => {
        const { data } = response || {};
        setData(data);
        setIsLoading(false);
      })
      .catch((error) => console.error(error));
  }, []);

  return (
    <DashboardLayout>
      {isLoading && (
        <TableRow sx={{ my: "1rem", padding: "6px 18px" }}>
          <Typography whiteSpace="pre" m={0.75} textAlign="left">
            <Skeleton variant="text" />
          </Typography>
          <Typography flex="1 1 260px !important" m={0.75} textAlign="left">
            <Skeleton variant="text" />
          </Typography>

          <Typography whiteSpace="pre" textAlign="right" color="grey.600">
            <Skeleton variant="text" />
          </Typography>
        </TableRow>
      )}

      {data?.length > 0 &&
        data.map((row) => (
          <TableRow sx={{ my: "1rem", padding: "6px 18px" }} key={row.id}>
            <Typography whiteSpace="pre" m={0.75} textAlign="left">
              {row.attributes.name}
            </Typography>
          </TableRow>
        ))}
    </DashboardLayout>
  );
};

export default AdresList;

And the code of function

export const getXAddress = async () => {
  const response = await apiClient.get("/adress");
  return response.data;
};

I will be grateful for help.

There are a little issue in your code.

I saw that when the useEfect make a request, you are handling the response in a wrong way when do this const { data } = response || {}; const { data } = response || {};

So if response is undefined the code gives {} (empty object). And next, when this part: setData(data); was runned, your array is replaced by undefined, resulting in problems like:

TypeError: Cannot read property 'map' of undefined.

Do this:

  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    getXAddress()
      .then((response) => {
        if (response) setData(response.data);
      })
      .catch((error) => console.error(error))
      .finally(() => setIsLoading(false));
  }, []);

Look that I move your setIsLoading(false) to finally , because if your Promise dispatch a catch() isLoading will be still true.

And the last. Watch out with your getXAddress function. Make sure that data will pass away or will be returned only the value. Otherwise will result in:

Cannot read data from undefined

export const getXAddress = async () => {
  const response = await apiClient.get("/adress");
  //Do this if you want to use de "response.data" at "then()"
  return response;
  //Or this if you want to use only "response" as result at "then()"
  return response.data;
};

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