"Encountering an issue with Next.js where the Redux

Hey there, I'm working on a simple project using Nextjs. I need to access the state of my Redux store but I'm encountering an error when trying to use store.getState, it's throwing an error saying getState is undefined. Additionally, I have a basic vanilla JavaScript file where I also want to utilize getState. Any suggestions on how to achieve this?

//store.js

import { useMemo } from "react";
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { rootReducer } from "./reducer";
import { exampleInitialState } from "./reducer";
let store;

const persistConfig = {
  key: "primary",
  storage,
  whitelist: ["exampleData", "count"], // place to select which state you want to persist
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

function makeStore(initialState = exampleInitialState) {
  return createStore(
    persistedReducer,
    initialState,
    composeWithDevTools(applyMiddleware())
  );
}

export const initializeStore = (preloadedState) => {
  let _store = store ?? makeStore(preloadedState);

  if (preloadedState && store) {
    _store = makeStore({
      ...store.getState(),
      ...preloadedState,
    });
    store = undefined;
  }

  if (typeof window === "undefined") return _store;
  
  if (!store) store = _store;

  return _store;
};

export function useStore(initialState) {
  const store = useMemo(() => initializeStore(initialState), [initialState]);
  return store;
}

//_app.js

import { useStore } from '../store'
import { Provider } from 'react-redux'
import { persistStore } from 'redux-persist'
import { PersistGate } from 'redux-persist/integration/react'

export default function App({ Component, pageProps }) {
  const store = useStore(pageProps.initialReduxState)
  const persistor = persistStore(store, {}, function () {
    persistor.persist()
  })

  return (
    <Provider store={store}>
      <PersistGate loading={<div>loading</div>} persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
    </Provider>
  )
}

vinall.js - How can i use store.getState in this file

import React from "react";
import { useStore } from "../store";
function vanilla() {
  
  return <div>i m vanilla js file</div>;
}

export default vanilla;

//Also in this file

import { useStore } from "../store";
function simplejs() {
  
  let state=useStore.getState();
  return state.tods;
}

Answer №1

If you want to retrieve data from your redux store, simply utilize the useSelector hook provided by react-redux. Here's an example of how to use it:

const myData = useSelector((state) => state.myData);

Answer №2

let myCustomReducer = persistReducer(persistConfig **as any**, rootReducer)

let customStore = createStore(myCustomReducer, applyMiddleware(sagaMiddleware));`

bold statement

`One can argue that its datatype is determined for utilization

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

Process Cancelled (Issue: ENOENT - file or directory not found[...])

Upon deploying my code on Vercel, I encountered an issue that was not present in my local environment. Despite searching extensively, I have been unable to find a solution for this problem. Aborted(Error: ENOENT: no such file or directory, open &apos ...

using JavaScript to send numerous text box values to various views

I have a dilemma with passing values between two views. In View1, there are text boxes for entering basic information. After the customer enters this data and clicks on 'add more details', I want to transfer these details to the text boxes in Vie ...

Breaking down and analyzing XML information

I have data that I need to retrieve from an XML file, split the result, parse it, and display it in an HTML element. Here is a snippet of the XML file: <Root> <Foo> <Bar> <BarType>Green</BarType> &l ...

Accessing a parent class constructor object in NodeJS from the Child Class

I'm currently working on creating a Controller Class that will handle the initialization of all my routes using ExpressJS. Below is a simple example of what I have so far: class Test extends Controller { constructor(App) { const Routes = [ ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

What is the process for transferring an object to a different file?

Currently, I am working on a web application using Node.js. In my project, I have two main files. The first one is Server.js, where I handle server actions such as going online. The second file contains a large object filled with data. I successfully impo ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

What is the best way to send information from one screen to a flatlist in React Navigation?

Currently, I am retrieving data from an API in the form of a JSON file. My goal is to pass this data from the main app to the appStack and then to the sessionsStack before displaying it on the home page. However, my console logs indicate that the data only ...

Integrating MongoDB data values with Node.js for enhanced functionality

Hey everyone, I'm looking to add two field values {type:Number} from a MongoDB collection using node js and then store the result back in the same collection. To achieve this, I have outlined the steps below: Retrieve the data value from MongoDB wit ...

Unexpected session error in NEXT.js app router with NextAuth: Session is not defined

I have implemented NextAuth with NEXT.js app router for authentication. The dashboard component is enclosed within an auth-guard that verifies whether the user is authenticated or not. Here is the code snippet for the auth-guard. export default function A ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

How to send parameters to the jQuery delete button click event handler

Here is the jQuery code I am working with: $('#btnDelete').click( function() {//Do the delete here via jquery post}); In my table, each row has a delete button like this: <a id="btnDelete">Delete</a> I need to pass parameters to t ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

The NextJs router encountered an unknown key passed through the urlObject during the push operation

I have a Next.js/React application where I am utilizing the Next Router to include some queries in my URL. However, when using the following function, the Chrome Dev Console displays numerous warnings: const putTargetsToQueryParams = (targets: IFragrance ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...