Home > Back-end >  I can't get the length of the data I call with useEffect
I can't get the length of the data I call with useEffect

Time:09-30

I get an error when I call data in a new useEffect. I tried new useEffect but not working. What I want to do is map this data in useEffect and set it into the state. I will send this state as parameter.

const [data, setData] = useState();
useEffect(() => {
    const reqObj = {
      page: "1",
      size: "10",
      sort_field: "id",
    };
    getWalkthroughs(reqObj)
      .then((response) => {
        if (response?.success) {
          setData(response?.data?.writeups);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log("err", err);
      });

  }, []);

console.log(data) //working
console.log(data.length) //length error

CodePudding user response:

By "length error" I suspect you mean something like "can not read properties of undefined".


The initial state value is undefined:

const [data, setData] = useState();

So you can't access any properties on it. You can use optional chaining so it only tries to access the property if the object exists:

console.log(data?.length);

Or only conditionally try to access it:

if (data) {
  console.log(data.length);
}

Or give the state value an initial empty array:

const [data, setData] = useState([]);
  • Related