best way to retrieve state from redux-toolkit (excluding initial state) in a Next.js environment

I am attempting to access the state of redux-toolkit in Next.js's getStaticProps

(After saving the accessToken in the store, I need to access the store from getstaticprops for the API it requires)

Here's what I have tried:

export default function Page({ state }) {
  console.log(state)
  return <>...</>
}
export const getStaticProps = wrapper.getStaticProps((store) => {
  return async () => {
    const state = store.getState()
    return {
      props: {
        state
      }
    }
  }
})

I was able to successfully access the state and checked it on Redux DevTools where it appeared as the initial (empty) state.

redux devtools.img

console.log.img

This is my redux toolkit setup on Next.js

//_app.js

import { wrapper } from '../store'

function MyApp({ Component, pageProps }) {
  axios.defaults.withCredentials = true
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default wrapper.withRedux(MyApp)
/store/index.js

import { configureStore } from '@reduxjs/toolkit'
import { createWrapper } from 'next-redux-wrapper'
import logger from 'redux-logger'
import reducer from './modules'

const makeStore = (context) =>
  configureStore({
    reducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(/*logger*/),
    devTools: process.env.NODE_ENV !== 'production'
  })

export const wrapper = createWrapper(makeStore, {
  debug: process.env.NODE_ENV !== 'production'
})


/store/modules/index.js

import { combineReducers } from '@reduxjs/toolkit'
import { HYDRATE } from 'next-redux-wrapper'

import timer from './timer'
import user from './user'
import cart from './cart'

const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    return {
      ...state,
      ...action.payload
    }
  }
  return combineReducers({
    user,
    timer,
    cart
  })(state, action)
}
export default reducer

/store/modules/user.js
import { createSlice } from '@reduxjs/toolkit'

const initialState = { userInfo: null, token: null, address: null }

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    getNewToken: (state, action) => {
      state.token = action.payload
    },
    getUserInfo: (state, action) => {
      state.userInfo = action.payload
    },
    getAddress: (state, action) => {
      state.address = action.payload
    }
  }
})

export const { getUserInfo, getNewToken, getAddress } = userSlice.actions
export default userSlice.reducer

Answer №1

getStaticProps executes on the server without any understanding of the client's activities. This occurs even during site generation, which could range from moments to years before the user interacts with the page. As a result, you will not be able to access the client-side Redux store and each time it will present a new Redux state due to uncertainty regarding how the client reached that page.

While you can trigger actions using dispatch within getStaticProps and then retrieve the resulting state through getState, it will always remain unique to each getStaticProps call.

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

AngularJS 500 server error

In my current project, I am developing a straightforward angularjs - J2EE application that fetches data from a mysql server and then displays it on an HTML page. The angular function is triggered on form submission as shown below: <div id="register_for ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

How about this: "Looking to Share on Social Media with ME

After developing an app using MEAN.js, I made enhancements to the Articles (blog) section to improve SEO, readability, and design. However, one issue I'm struggling with is how to properly share these Articles on social media platforms like Facebook, ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...

Can Authorization be Combined with Filtering in a Node.js RESTful API?

In my current setup, I have a web application communicating with a RESTful API to interact with the database. The frontend of the web app uses Angular HTTP to post/get/put data to the backend, which then manages authentication, interacts with the API, and ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

Functionality of retrieving arrays from PHP via jQuery ajax (JSON) runs smoothly, however encounters issues specifically on web server

No solutions have been able to solve the problem at hand despite finding similar questions. function loadProject(id) { $.ajax({ url: 'loadDrumsetData.php', type: 'GET', data: { i: id }, ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

Save an HTML5 canvas element as a picture using JavaScript and specify the file extension

Is there a way to save an Html5 canvas element as an image file using Javascript? I've tried using the CanvasToImage library, but it doesn't seem to work for this purpose. You can view my current code on JsFiddle. <div id="canvas_container" ...

Dividing ReactJS into different assemblies

I have a flexible .NET application that utilizes plugins to load controllers, views, and components from different assemblies. I am interested in learning React (completely new to me) and I have a question. Can React split its components into separate as ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

React Context - Ensure synchronized deletion of user posts across routes while maintaining pagination during fetching

INTRODUCTION I am striving to replicate the behavior commonly seen in social networks, where deleting a post by a user results in its automatic removal across all app routes. This functionality is reminiscent of how platforms like Instagram or TikTok oper ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

Revolutionary scroll-based navigation fill transition

I'm attempting to achieve an effect where the fill color of the "insticon" SVG changes from black to white based on the scroll position indicated in the jQuery code. I have made the necessary modifications in the if and else statements, but unlike "he ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...