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

Having success loading JSON with AJAX in a local browser, however encountering issues when attempting to do so within the PhoneGap

When I try to load external JSON-data locally in my browser, it displays the data successfully. However, when using a cloud-based build service like PhoneGap for iOS and Android apps, the page loads but without the JSON-data appearing. Can anyone provide a ...

What are the differences between using attachShadow with the "mode" set to open compared to closed

I've recently delved into the world of Shadow DOM through some casual video watching. It seems like many people are quick to dismiss this feature, with comments like "Just keep it open" and "It's less flexible when closed." attachShadow( { mode ...

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Setting up an event listener for a newly added list through the use of node appendChild

I am currently working on dynamically adding a select list to my HTML document. While I have successfully added the node to the DOM, I am struggling with creating an event listener in a separate JavaScript file that recognizes the newly created select list ...

Issues arise when attempting to use Redux dev tools in conjunction with Next.js, Redux toolkit, and Redux Saga

Having some trouble getting Redux dev tools to cooperate with my setup: Next.js 13 (App folder) Redux toolkit Redux saga The issue I'm encountering is the inability to view the state consistently. There are times when it works, especially after pinn ...

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

When utilizing the dispatch function with UseReducer, an unexpected error is triggered: Anticipated 0 arguments were provided,

Having trouble finding a relevant answer, the only one I came across was related to Redux directly. So here's my question that might be obvious to some of you. In my code, everything appears to be correct but I'm facing an error that says: Expect ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

Looking to efficiently output information generated within a headless browser in node.js

Is there a way to print out data created inside a Node.js running headless browser if console.log('Text') isn't working? For example: const pup = require('puppeteer'); const chrom = await pup.launch({headless:'new'}); ...

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Is it possible to activate the jQuery .click() function for a button with specific text?

Here's a dilemma I'm facing: $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s ...

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Any suggestions on resolving the "script timeout" issue while running a script using Python's SeleniumBase Library?

Recently starting to use Python, I am currently using Python's seleniumbase library to scrape a website and need to periodically run this fetch script. While experimenting, I encountered a script timeout error when the response time exceeded around 95 ...

What steps should I take to stop material-ui Select options from opening when clicking on specific parts of the selected option?

Presently, I am utilizing a Select component from @material-ui/core/Select, which contains only one option for simplification purposes, and the code snippet is as follows: <FormControl> <InputLabel id="demo-controlled-open-select-label">Test ...

Setting an HTML element ID on a material-ui component: A step-by-step guide

I have a website that was created using Gatsby.js and incorporates the Material-UI framework. The specific issue at hand is as follows: I am looking to implement Google Tag Manager "Element Visibility" triggers. The goal is for GTM to trigger a Google Ana ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

In Three.js, FBX bones exhibit smooth rotation, but GLTF bones display strange rotation behavior

Currently, I have successfully implemented a dynamic model that works with an FBX file using the Three.js FBXLoader. However, for convenience sake, I decided to switch to using a GLTF/GLB file as it contains textures within the same file. To achieve this, ...