Reputation: 11
I am working on a project where I need information to be displayed in real time. For this, I am using nextjs and swr. By copying the examples provided at https://swr.vercel.app/es-ES/examples/ssr I am not able to display data on the screen. Can someone give me some light?
I created a new project with:
npx create-next-app --example hello-world hello-world-app
I copied the source from SWR Vercel web and nothing it has happened.
My package.json is:
{
"name": "swr-ssr",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"post-update": "yarn upgrade --latest"
},
"dependencies": {
"next": "latest",
"react": "18.2.0",
"react-dom": "18.2.0",
"swr": "2.0.0"
},
"license": "MIT",
"keywords": [],
"description": ""
}
And my index.js is:
import useSWR, { SWRConfig } from "swr";
const fetcher = (url) => fetch(url).then((res) => res.json());
const API = "https://api.github.com/repos/vercel/swr";
export async function getServerSideProps() {
const repoInfo = await fetcher(API);
return {
props: {
fallback: {
[API]: repoInfo
}
}
};
}
function Repo() {
const { data, error } = useSWR(API);
// there should be no `undefined` state
console.log("Is data ready?", !!data);
if (error) return "An error has occurred.";
if (!data) return "Loading...";
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{" "}
<strong>✨ {data.stargazers_count}</strong>{" "}
<strong>🍴 {data.forks_count}</strong>
</div>
);
}
export default function App({ fallback }) {
return (
<SWRConfig value={{ fallback }}>
<Repo />
</SWRConfig>
);
}
Upvotes: 1
Views: 378
Reputation: 1
If use server component, you cant import useSWR, { SWRConfig } from "swr"
on server component. You should use import { unstable_serialize } from 'swr'
[1]: https://swr.vercel.app/docs/with-nextjs
If using client component, add use client
at the top of file and pass fetcher
function on hooks useSWR() parameter
'use client'
import useSWR from "swr";
const fetcher = (url) => fetch(url).then((res) => res.json());
const API = "https://api.github.com/repos/vercel/swr";
function Repo() {
const { data, error } = useSWR(API, fetcher);
console.log(data)
/// rest of code
}
Upvotes: 0