Jotai createStore does not work with next.js
Unanswered
American Shorthair posted this in #help-forum
American ShorthairOP
: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
{get: function readAtom, set: ..., sub: ..., dev4_get_internal_weak_map: ..., dev4_get_mounted_atoms: ..., dev4_restore_atoms: ...}But when I make it use server it gives different error
Error: A "use server" file can only export async functions, found object.
Read more: https://nextjs.org/docs/messages/invalid-use-server-value3 Replies
American ShorthairOP
code:
"use server";
import type { Metadata } from "next";
import "./globals.css";
import "./fonts.css";
import Navbar from "../_components/Navbar/Navbar";
import { createStore, Provider } from "jotai";
import { cookies } from "next/headers";
import { jwtDecode } from "jwt-decode";
import { IJWTPayload, USER_ROLE } from "../_lib/types/global.types";
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
async function getUserData() {
const cookie = cookies().get("refresh_token");
if (cookie) {
const response = await fetch(
`${process.env.SERVER_URL}/auth/refresh_token`,
{
headers: {
Cookie: cookies().toString(),
},
}
);
const data = await response.json();
if (data.success) {
const userData = jwtDecode<IJWTPayload>(data.payload);
return { ...userData, token: data.payload };
} else {
return {
id: "",
role: [USER_ROLE.USER],
avatar: "",
token: "",
};
}
} else {
return {
id: "",
role: [USER_ROLE.USER],
avatar: "",
token: "",
};
}
}
const store = createStore();
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const userData = await getUserData();
return (
<html lang="en">
<body>
<Provider store={store}>
<Navbar data={userData} />
{children}
</Provider>
</body>
</html>
);
}Sun bear
You shouldn't use jotai store when using next.js. You can just leave the jotai provider store undefined:
// layout.tsx
import { Provider } from "jotai"
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>
<Provider>
{children}
</Provider>
</body>
</html>
)
}@Sun bear You shouldn't use jotai store when using next.js. You can just leave the jotai provider store undefined:
tsx
// layout.tsx
import { Provider } from "jotai"
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>
<Provider>
{children}
</Provider>
</body>
</html>
)
}
Amur catfish
what if you need to access state outside of react though?