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>
);
}
With this code props?.restaurantData[0]
you are not checking that restaurantData is not null, but only props.
Replace it with (props?.restaurantData?.length && props.restaurantData[0]) || []
(props?.restaurantData?.length && props.restaurantData[0]) || []
There are better ways to handle it, but it depends on your use case
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.