Home > other >  React Uncaught TypeError when accessing data from axios get request (data is undefined)
React Uncaught TypeError when accessing data from axios get request (data is undefined)

Time:10-15

Im trying to get data from a collection stored in MongoDB. When i try to get the data in Insomnia everything works fine. When i make a request with axios i get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'games')

I use a custom Hook

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

const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);

useEffect(() => {
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get(url);
      setData(res.data);
    } catch (err) {
      setError(err);
    }
    setLoading(false);
  };
  fetchData();
}, [url]);

const reFetch = async () => {
  setLoading(true);
  try {
    const res = await axios.get(url);
    setData(res.data);
  } catch (err) {
    setError(err);
  }
  setLoading(false);
};

return { data, loading, error, reFetch };
};

export default useFetch;

Then i call the useFetch Hook as you can see in the third code block. When i try to call data[0].games i get the undefined error but when i just call data[0] there is no error and the data is printed in the console. Here is also the mongoDB model i defined for this case:

import mongoose from "mongoose";

const SpielSchema = new mongoose.Schema({
    heimName: {
        type: String,
        required: true
    },
    heimTore: {
        type: Number,
        required: true
    },
    auswName: {
        type: String,
        required: true
    },
    auswTore: {
        type: String,
        required: true
    },
});

const TippsSchema = new mongoose.Schema({
    number: {
        type: Number,
        required: true
    },
    date: {
        type: String, 
        required: true
    },
    user: {
        type: String, 
        required: true
    },
    userId: {
        type: String, 
        required: true
    },
    games: [SpielSchema]
})

export default mongoose.model("Spieltag", TippsSchema)

As soon as i want to access any data in data[0]. (number, date, user, userId, games) i get this error. And here you can see the react code where i call useFetch to get the data. At the moment this is only test code so its hopefully more clear to you :)

export const Spieltagtipps = (props) => {
  const { user } = useContext(AuthContext);
  const { data, loading, error, reFetch } = useFetch("tipps/find/" user.username);
  return (
    <>
    {loading ? (
      <h1>Loading...</h1>
    ) : (
    <>
     {data && <h1>{console.log(data[0].games)}</h1>}
    </>
    )
    }
    </>
    )

Here you can see the two outputs:
Error when i call data[0].games
No error when i call data[0]

CodePudding user response:

you have to check the length of an array as the condition to render as below

{data.length > 0 && <h1>data[0].games</h1>}

you can check the falsy values in JS

consider rest all which are not in above list as true and passes the condition and so [] passes too

  • Related