Reputation: 65
I am using next js in my project when i fetch from my server using useswr hook then there is certain condition to return on the page for example
import InnerNavbar from "../components/InnerNavbar";
import DashboardLoadingSkeleton from "../components/DashboardLoadingSkeleton";
import DashBoardData from "../components/DashBoardData";
import useSWR, { mutate } from "swr";
const fetcher = async () => await fetch(`${process.env.NEXT_PUBLIC_URL}/fetchchallenges`, {
method: "POST",
credentials: 'include'
}).then((res) => res.json());
const dashboard = () => {
const { data, error } = useSWR("/dashboard", fetcher, { dedupingInterval: 40000 });
if (!data) {
if (!data.Errors) {
return (<><InnerNavbar /><DashBoardData data={data} mutate={mutate} /></>);
} else if (data.Errors === "Not Approved") {
return (<>{location.replace('/notapproved')} <center><h1>Not Approved By Admin</h1></center></>)
}else {
return (<>{location.replace('/logout')} <center><h1>Redirecting...</h1></center></>)
}
} else {
return (
<>
<InnerNavbar />
<DashboardLoadingSkeleton />
</>
)
}
};
export default dashboard;
now i want to need this same conditional statement in multiple pages to return but i don't known how to create a separate function for that.
Upvotes: 1
Views: 532
Reputation: 3577
I think you can use react Higher-Order Components
here is sth that I made:
import useSWR, { mutate } from "swr";
const fetcher = async () => await fetch(`${process.env.NEXT_PUBLIC_URL}/fetchchallenges`, {
method: "POST",
credentials: 'include'
}).then((res) => res.json());
const withSwrData = ({Component,endpoint}) => {
const { data, error } = useSWR(endpoint, fetcher, { dedupingInterval: 40000 });
if (!data) {
if (!data.Errors) {
return (<Component data={data} mutate={mutate} />);
} else if (data.Errors === "Not Approved") {
return (<>{location.replace('/notapproved')} <center><h1>Not Approved By Admin</h1></center></>)
}else {
return (<>{location.replace('/logout')} <center><h1>Redirecting...</h1></center></>)
}
} else {
return (
<>
<Component />
</>
)
}
};
export default withSwrData;
and use it in dashboard in this way :
import InnerNavbar from "../components/InnerNavbar";
import DashboardLoadingSkeleton from "../components/DashboardLoadingSkeleton";
import DashBoardData from "../components/DashBoardData";
import withSwrData from "../withSwrData"
const dashboard = ({data,mutate}) => {
return (<>
<InnerNavbar />
{data ? <DashBoardData data={data} mutate={mutate} /> : <DashboardLoadingSkeleton /> }
</>)
};
export default withSwrData(dashboard,"/dashboard");
Upvotes: 1