Utilizing Zustand state management with Next.js 13.4.12 for routing and server-side rendering, enhanced with local storage

My Zustand store code looks like this:

import create from "zustand";
import { persist } from "zustand/middleware";

const useProjectStore = create(
  persist(
    (set) => ({
      selectedProject: null,
      setSelectedProject: (project) => set({ selectedProject: project }),
    }),
    {
      name: "food-storage", // unique item name in storage
      // (optional) by default, 'localStorage' is used
    }
  )
);

export default useProjectStore;

I need to use this store on a page where I will retrieve the state of the current selected project and then update the Prisma query using the project ID from the state:

import { prisma } from "@/lib/prismaDb";
import ImageList from "@/app/dashboard/components/imageList";
import ImageTable from "@/app/dashboard/components/imageTable";
import useProjectStore from "@/stores/currentProject-store";
import useServerStore from "@/stores/useServerStore";

const imagesPage = async () => {
  const useProjectStore = useServerStore((state) => state.useProjectStore);
  console.log("useProjectStore", useProjectStore);
  const imageList = await prisma.facebookImage.findMany({
    where: {
      projectId: "f2b78a6f-160f-4b2c-9cd5-b98c2f04d0d0",
    },
  });

  console.log("imageList2222");

  console.log("superaman", imageList);
  return (
    <div>
      <ImageTable imageList={imageList} />
      {/* <ImageList imageList={imageList} /> */}
    </div>
  );
};

export default imagesPage;

The issue I'm facing is that local storage cannot be accessed from the server. Is there any way to resolve this?

I have explored this solution - mentioned in the Zustand documentation, but it resulted in an error stating that hooks cannot be used on the server side.

If you have any questions, feel free to ask. Thank you.

Answer №1

To transform a regular component into a client component, simply include "use client" at the top of the file. This allows hooks to be utilized within client components. Alternatively, if you want your imagePage to be a client page, add "use client" at the beginning of the page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to disable the Next.js 14 cache for static sites, such as setting the output to "export"?

When running next build with the output: "export" option, API calls are cached and any changes do not reflect in the resulting static files. Is there a way to turn off caching or update the data during the build process? Configuration Details: ...

Can I deactivate JavaScript on my website directly from my server settings?

I'm currently attempting to link my Android application to a PHP script hosted on a free server. However, when my app tries to access the page, I receive an HTML message stating that JavaScript is disabled and needs to be enabled in order to view the ...

The array is coming back empty after attempting to add objects to it

My Node JS and Express JS controller code is below: const UserComment = require(".../model/UserComment"); router.post("/get/comments", async (req, res) =>{ try{ let currentUserID = req.body.userID; let myUserComment = await UserComment.find({userID: cu ...

Passing a MySQL connection to scripts in Express

After setting up the mysql connection with all the required parameters in app.js, is there a way to make it accessible to other scripts in routes/ without having to redeclare or require the mysql parameters again, simply by using client.query(..)? ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

Having trouble with Passport.js authentication not functioning properly

Setting up passport for the first time and opting for a single Google sign-in option. I've gone through the process of registering with Google APIs to get everything set up. However, when my app calls '/auth/google/', it fails without any re ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

How selection.join behaves when every node contains child elements

I have been following the amazing tutorial on to learn more about the join paradigm. Everything was working fine until I tried to make each node more complex by adding a group with text inside. The main group gets updated, but the child one does not. Sn ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Error: The 'Window' object is not defined. The use of Client in NextJS13 is not

I've been attempting to integrate NextJS 13 with react-leaflet, but I keep encountering the error "window is not defined" when running my component. I attempted using the "use client" declaration at the beginning of the file and adding a check for "ty ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

My API encountered a 404 error when trying to access the MAILCHIMP API

I am currently working on a project focused on creating a Newsletter for web development led by Angela Yu. In this project, I encountered a 404 error while integrating the API from the MAILCHIMP website. Each time I tried to insert the API, it consistent ...

NextAuth: Having difficulty redirecting to the page for New User registration

I can't seem to understand why the redirection to the NewUser page isn't working when a user Signs In with the CredentialsProvider. The authorize function clearly returns the "isNewUser" flag as true for new users. Take a look at the configurati ...

JavaScript and Responsive Design Techniques

I'm struggling to create a responsive page that starts with a mobile-first approach, but I keep running into the same issue. When I have my dropdown menu in the mobile version, it looks good. However, when I try to switch it to the non-mobile version ...

Struggling to import MUI components from node modules in your React JavaScript project using Vite? Discover why autosuggestion isn't getting the

Encountering a dilemma with autosuggestion in Visual Studio Code (VSCode) while attempting to import MUI (Material-UI) components from node modules in my React JavaScript project built with Vite. The autosuggestion feature is not working as intended, causi ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

The post processing effect in Three.js does not support FXAA when SSAO is activated

I am having trouble getting SSAO and FXAA effects to work together in this simple test scene. Enabling SSAO works fine, but when I also enable FXAA, the render turns black. In the provided fiddle, if you uncomment composer.addPass(FXAA_effect); you will s ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...