I am trying to get used to Next.js’ version. Before I was using getServerSideProps and sending the data to client side so I was getting the data at first render without seeing undefined. I didn’t understand how to achieve the same thing in the latest version (next.js 14).
Here is my code:
Home page:
"use client";
import { useState } from "react";
import ListTasks from "@/components/ListTasks/ListTasks";
import Modal from "@/components/Modal/Modal";
import useGetData from "@/hooks/useGetData";
export default function Home() {
const [modalProps, setModalProps] = useState({
isOpen: false,
type: "",
});
const data = useGetData();
console.log(data);
return (
<div className="bg-slate-500 w-screen h-screen flex justify-center items-center">
{modalProps.isOpen && (
<Modal modalProps={modalProps} setModalProps={setModalProps} />
)}
<div className="bg-gray-400 w-1/3 h-3/4 rounded">
<p className="text-white text-center text-2xl font-bold">To-do App</p>
<div className="w-10 h-10 bg-black rounded flex justify-center items-center cursor-pointer">
<p
className="text-white text-6xl pb-2"
onClick={() =>
setModalProps({ ...modalProps, isOpen: true, type: "post" })
}
>
+
</p>
</div>
<div className="bg-red-300 indent-5 rounded m-3 py-1">
<ListTasks modalProps={modalProps} setModalProps={setModalProps} />
</div>
</div>
</div>
);
}
useGetData hook:
import useSWR from "swr";
export default function useGetData() {
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const { data, error, isLoading } = useSWR("/api/get", fetcher);
return data;
}
What can I do to get the data at first render without seeing undefined?
2
Answers
In the main page
When you navigate to a page that uses
getServerSideProps
, Next.js runs this function during the server-side rendering (SSR) process. The data fetched ingetServerSideProps
is then passed as props to your React component, allowing you to have access to it on the first render without the initial state beingundefined
. This eliminates the need to handle loading states for data fetching on the initial page load, as the page is served with all the necessary data already in place.swr
is reach hook library, hook library can be run only client side. when you do client side data fetching, fetching starts only after the JavaScript has loaded and the React component has mounted. This means the initial render of the component doesn’t have the fetched data. Because fetching data from the client side is asynchronous, the component renders initially without the data, necessitating handling of loading states. During the initial fetch, SWR transitions to a loading state. While in the loading state, you typically display a loading spinner. Once the data fetching is complete,SWR
transitions from the loading state to the data state. The component re-renders with the fetched data, allowing you to display the actual content to the user.