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

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

Integration with Node.js API for enhanced authentication

I have implemented Next Auth in combination with a standalone Node.js API in my project. Utilizing credentials, I am using axios to transmit the username and password to the API. Upon successful authentication on the API side, I establish a session using ...

What are some effective strategies for incorporating multiple Themes into an AngularJS project?

Currently, I am in the process of working on a project that involves utilizing AngularJS, UI Bootstrap, and Sass. The next step is to incorporate different themes that can be selected by the user. While I have successfully implemented the ability to apply ...

Deleting elements from the DOM in Vue.js

Utilizing Vue.js (version 3.x), I am dynamically rendering components. <div v-for="(i, index) in fields" > <my-component :id="index" ></my-component> <span class="delete-icon" @click="removeFi ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

Having trouble resolving the dependency tree within react-navigation-stack

Trying to understand navigation in React-native and attempting to execute the following code: import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import {createAppContainer} from 'react-nav ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...

Sorting by price using the ng-repeat directive is not suitable for this

Utilizing angular's ng-repeat along with orderBy on a product catalog page to sort the products based on a select change. The ordering by name using orderBy works as expected, however, when it comes to price it sorts like this: 1,10,11,12,13,14,2,3,4 ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

Laravel Next-Auth credential provider encounter - Error 419 occurred during request processing

Currently, I have set up a NextJS Frontend with Next-Auth combined with a Laravel Backend using Sanctum authentication. However, when attempting to log in utilizing the signIn function of Next-Auth, an error is encountered: Request failed with status code ...

Vertical Orientation in HTML

Would appreciate some assistance on creating a vertical text with HTML similar to the example in the linked screenshot. It needs to be straightforward and vertically oriented. Check out the screenshot for reference ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

XML is struggling to load content when using ajax requests

I am attempting to utilize ajax to load an xml file. I have made adjustments to the sample code provided by W3Schools <html> <head> <script> function showBus(str) { if (str == "") { ...

The transfer of variables from AJAX to PHP is not working

My attempt to pass input from JavaScript to PHP using AJAX is not successful. I have included my JS and PHP code below: <!DOCTYPE html> <html> <head> <style> div{border:solid;} div{background-color:blue;} </style> </head&g ...

Embrace positive practices when working with nodejs

What is the best way to enhance the readability of my code by replacing the extensive use of if and else if statements when detecting different file extensions? Currently, I have over 30 else ifs in my actual code which makes it look cluttered. // Retrie ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

Obtaining an image from a URL, saving it, and then animating it? That definitely

Looking to create a dynamic animation with images that update every 15 minutes from the following URL: How should I go about storing and looping through the most recent 24 images for the animation? Is using a MySQL database the best option or are there o ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...