Home > OS >  Cannot read properties of undefined (reading 'length') when looping over state
Cannot read properties of undefined (reading 'length') when looping over state

Time:11-26

Hi everyone can I know why the state that is filled with values from api using useEffect, does not loop through data as long as I provide the "?" mark before .map function or before length prop ? Code: 1- defining the state:

  const [userInProgressTasks, setUserInProgressTasks] = useState();

2- Getting the data from the api:

useEffect(() => {
    let isMounted = true;
    //to cancel our request if the component is unmounted
    const controller = new AbortController();
 const getUserTasksInProgress = async () => {
      try {
        const response = await axiosPrivate.get(
          ApiConstants.GETALL_USER_IN_PROGRESS_TASKS_ENDPOINT(userObject?.id),
          {
            signal: controller.signal,
          }
        );
        console.log(response?.data);
        isMounted && setUserInProgressTasks(response?.data);
      } catch (err) {
        console.err(err);
        //in case of error (exipre of refresh token) - send them back to login
        navigate("/auth/login", {
          state: { from: location },
          replace: true,
        });
      }

getUserTasksInProgress();

    //clean up function of useEffect - it runs when the component unmount
    return () => {
      isMounted = false;
      //cancel any request when the component unmount
      controller.abort();
    };

  }, []);

    };

3- looping through the state:

              {userInProgressTasks?.length <= 0 ? (
                <>
                  <div className="NoTasks-Image-Container">
                    <img src={InProgressImage} />
                  </div>
                </>
              ) : (
                <>
                 {userInProgressTasks?.map((t) => (
                  <p>{t.taskId}</p>
                 )  )}
                </>
              )}

Any ideas why ? does the mark '?' wait for the state to be filled or something like related ?

CodePudding user response:

The lifecycle is the following:

  1. useState is set first with undefined for userInProgressTasks
  2. render
  3. useEffect

That's why it asks you to safeguard values with ? because they can be undefined I'd suggest always initializing your state

  const [userInProgressTasks, setUserInProgressTasks] = useState([]);
  • Related