I have a server component that consists of a fetch request to get data, for example, categories. The fetch function on the server side works as expected but I need somehow to store this data in a store/state that my whole website can access.
import { atom, useAtom } from "jotai";
import MainNav2Logged from "./MainNav2Logged";
export interface HeaderLoggedProps {}
const categoriesAtom = atom([]);
async function getData() {
const res = await fetch("https://api.escuelajs.co/api/v1/categories");
if (!res.ok) {
throw new Error("Failed to fetch data");
}
const data = await res.json();
categoriesAtom.set(data); // here is the problem
}
const HeaderLogged = () => {
const categories = useAtom(categoriesAtom);
return (
<div className="nc-HeaderLogged sticky top-0 w-full z-40 ">
<MainNav2Logged />
{categories.map((el) => (
<p key={el.id}>is it here? {el.name}</p>
))}
</div>
);
};
export default HeaderLogged;
But it gave me this error:
You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
,-[/home/ash/Desktop/diffandyol/node_modules/jotai/esm/react.mjs:1:1]
1 | import ReactExports, { createContext, useContext, useRef, createElement, useReducer, useEffect, useDebugValue, useCallback } from 'react';
: ^^^^^^^^^
2 | import { getDefaultStore, createStore } from 'jotai/vanilla';
3 |
4 | const StoreContext = createContext(void 0);
`----
The error was caused by importing 'jotai/esm/index.mjs' in './src/components/Header/HeaderLogged.tsx'.
By the way, I use the Next.js experimental App router, not the Pages router.