Cannot read properties of undefined (reading '0')

16,392

1-if data is undefined on the first component render I think this approach will work

  • first-time data is undefined
  • sec time data is fetched then u can use as below
const fetcher = async () => {
  const response1 = await fetch("API");
  const data1 = await response1.json();


  const props = {
    data: data1,
  };
  return props;
};
  • if look at ur fetching function u return props= {data: data1}
  • const {data} =useSWR("data",fetching) it should be data.data.showItemOnOrder
return (
    <Fragment>
      <Head>
        <title>Dashboard</title>
        <link rel="icon" href="/favicon.ico" />
       
      </Head>

      <LayoutDashboard restaurantData={props?.restaurantData[0]}>
       {data&& <DashboardPage
          orders={data.data.showItemsOnOrder}
          dashboardCards={data.data.dashboardCardInfo}
          ordersGraph={data.data.dashboardGraph}
        />}
      </LayoutDashboard>
    </Fragment>
  );
Share:
16,392

Related videos on Youtube

Floky99
Author by

Floky99

Updated on June 04, 2022

Comments

  • Floky99
    Floky99 almost 2 years

    I have a page coded in React with NextJS hooks, when I try to render a page the error says what's in the title, I presume because the object which I'm mapping is empty/undefined on first load. I added "?" to every map I have on the page and it's still giving me this error... I noticed that if I stay on that page after it gives me error and press "Ctrl + shift + r" the page loads normally. What could be causing this?

    import {Fragment, useEffect} from "react";
    import Head from "next/head";
    import DashboardPage from "../../../../components/components/dashboard/DashboardPage";
    import LayoutDashboard from "../../../../components/layout/LayoutDashboard";
    import React from "react";
    import Pusher from "pusher-js";
    import useSWR, {mutate} from "swr";
    
    const fetcher = async () => {
      const response1 = await fetch("API");
      const data1 = await response1.json();
    
    
      const props = {
        data: data1,
      };
      return props;
    };
    
    export default function Dashboard(props) {
      const {data, error} = useSWR("data", fetcher);
    
      useEffect(() => {
        //Pusher.logToConsole = true;
        var pusher = new Pusher("pshr", {
          cluster: "eu",
        });
        const channel = pusher.subscribe("chnl");
        channel.bind("chnl", function (data) {
          console.log(data);
          mutate("data");
        });
      }, []);
    
      if (error) return "Error";
      if (!data) return "Loading";
    
      console.log(data);
      return (
        <Fragment>
          <Head>
            <title>Dashboard</title>
            <link rel="icon" href="/favicon.ico" />
           
          </Head>
    
          <LayoutDashboard restaurantData={props?.restaurantData[0]}>
            <DashboardPage
              orders={data?.showItemsOnOrder}
              dashboardCards={data?.dashboardCardInfo}
              ordersGraph={data?.dashboardGraph}
            />
          </LayoutDashboard>
        </Fragment>
      );
    }
    
    export async function getStaticPaths() {
      const response = await fetch(`API`);
      const data = await response.json();
    
      const tables = [];
      for (var i = 1; i <= data[0].restaurantTables; i++) {
        tables.push({
          restaurant: data[0].queryName,
          tableNr: i.toString(),
        });
      }
    
      return {
        paths: tables.map((table) => {
          return {
            params: {
              restaurantName: table.restaurant,
              tableNr: table.tableNr,
            },
          };
        }),
        fallback: false,
      };
    }
    
    export async function getStaticProps() {
      const response = await fetch(`API`);
      const data = await response.json();
    
      return {
        props: {
          restaurantData: data,
        },
        revalidate: 1,
      };
    }
    

    EDIT I recognized that the site works normally if I go straight to the link that I want... It stops working when I'm calling components with Link tags in nextJS then it throws an error that it's in title... So if I go straight to the link everything works as expected maybe that is also the reason that the page works if I click on my link and then refresh it... So what could be the problem with Link tag? This is my code for it:

    <Link
           href={{
                  pathname: "/restaurant/restaurantName/dashboard/",
                  query: {restaurantName: restaurantName},
                }}
              >
                <div
                  className={
                    router.pathname == "/restaurant/[restaurantName]/dashboard"
                      ? "text-blue-600 bg-gray-50"
                      : "text-gray-700 "
                  }
                >
                  <div className="flex p-3  space-x-4 0 hover:bg-gray-50 hover:text-blue-600  cursor-pointer">
                    <DonutLargeIcon className=" text-gray-300" />
                    <p className="">Dashbord</p>
                  </div>
                </div>
              </Link>
    
    • Jacob
      Jacob over 2 years
      I think the error has to do with data[0] being undefined... check that your API request is working properly and giving you data you expect.
    • juliomalves
      juliomalves over 2 years
      In your fetcher function you're returning the data as { data: data1 }, meaning if you want to access the actual API data returned by useSWR you need to access data.data not just data.
    • Floky99
      Floky99 over 2 years
      @JacobLockwood Yes API request is working as expected since after the hard reload the page works normally...
    • Floky99
      Floky99 over 2 years
      @juliomalves but why does the page work after the reload and not on the first load?
    • juliomalves
      juliomalves over 2 years
      Do you still see the same issue if you fix the issue I mentioned?
    • Floky99
      Floky99 over 2 years
      I still see the same issue because data.data has no values... The data without the .data does in fact have its values but just not if I render a page via NextJS Link hook. But if I render the page via direct link of the page everything works...
  • Floky99
    Floky99 over 2 years
    I copied your code and replaced my useEffect with your code, the issue is still the same... TypeError: Cannot read properties of undefined (reading '0')
  • Floky99
    Floky99 over 2 years
    I added your piece to my code and the issue is still the same... TypeError: Cannot read properties of undefined (reading '0')
  • Dejan Janjušević
    Dejan Janjušević over 2 years
    @Floky99 Can you confirm that the API call in getStaticPaths returns valid JSON when this error happens?
  • Dejan Janjušević
    Dejan Janjušević over 2 years
    @Floky99 I think I know what caused it, see my edit.
  • Floky99
    Floky99 over 2 years
    I can confirm that the data from JSON is returned and it's valid since after the hard refresh shows up my page normally after error is shown on page... I also tried to add your edited code to my project and the problem still persists...
  • Floky99
    Floky99 over 2 years
    The problem lies in the fetching of the data for components nested in <DashboardPage/> because if I remove this component site works normally since props are fetched server side so first render doesn't have a problem with that, the problem is something with SWR fetching even tho I'm checking for if(!data) return loading...
  • Floky99
    Floky99 over 2 years
    Sorry but how is your code different than mine? It looks the same to me...
  • Dejan Janjušević
    Dejan Janjušević over 2 years
    @Floky99 you should have a stack trace printed in the console when the error occurs. Can you post that as well?
  • Floky99
    Floky99 over 2 years
    Uncaught TypeError: Cannot read properties of undefined (reading '0') at DashboardPage (DashboardPage.js:28) at renderWithHooks (react-dom.development.js:14985) at mountIndeterminateComponent (react-dom.development.js:17811) at beginWork (react-dom.development.js:19049) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056) at beginWork$1 (react-dom.development.js:23964)
  • Floky99
    Floky99 over 2 years
    at performUnitOfWork (react-dom.development.js:22776) at workLoopSync (react-dom.development.js:22707) at renderRootSync (react-dom.development.js:22670) at performSyncWorkOnRoot (react-dom.development.js:22293) at react-dom.development.js:11327 at unstable_runWithPriority (scheduler.development.js:468) at runWithPriority$1 (react-dom.development.js:11276) at flushSyncCallbackQueueImpl (react-dom.development.js:11322) at flushSyncCallbackQueue (react-dom.development.js:11309)
  • Floky99
    Floky99 over 2 years
    at scheduleUpdateOnFiber (react-dom.development.js:21893) at updateContainer (react-dom.development.js:25482) at legacyRenderSubtreeIntoContainer (react-dom.development.js:26037) at Object.render (react-dom.development.js:26103) at renderReactElement (index.js:483) at doRender (index.js:665) at _callee2$ (index.js:375) at tryCatch (runtime.js:63) at Generator.invoke [as _invoke] (runtime.js:294) at Generator.next (runtime.js:119) at asyncGeneratorStep (index.js:28) at _next (index.js:46) at index.js:51 at new Promise (<anonymous
  • Floky99
    Floky99 over 2 years
    at index.js:43 at render (index.js:396) at Router.subscription [as sub] (index.js:334) at Router.notify (router.js:1060) at Router.set (router.js:878) at Router._callee$ (router.js:730) at tryCatch (runtime.js:63) at Generator.invoke [as _invoke] (runtime.js:294) at Generator.next (runtime.js:119) at asyncGeneratorStep (asyncToGenerator.js:3) at _next (asyncToGenerator.js:25)
  • Dejan Janjušević
    Dejan Janjušević over 2 years
    @Floky99 and what is at DashboardPage.js:28 ?
  • Floky99
    Floky99 over 2 years
    function DashboardPage(props) { const [thisMonthOrders, setThisMonthOrders] = useState( props?.dashboardCards[0]?.orders?.thisMonth[0]?.orders //line 28 );
  • Dejan Janjušević
    Dejan Janjušević over 2 years
    @Floky99 so how do you expect to find the solution if you have posted an irrelevant part of the code? Also, you need to update the question with these new informations, not add them to some comments noone is likely to ever read,
  • BlueDragon
    BlueDragon over 2 years
    can you show me the console.log(data) from useSWR ? It's caused by your access object properties incorrectly
  • Floky99
    Floky99 over 2 years
    The data is correct... The page works after reload every time so there seems to be the problem with getting to page in the first attempt