question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Redux store not updating with SSR?

See original GitHub issue

I’ve got a component where the store updates fine on the client side with the following code:

  componentDidMount() {
    const { loadQuoteIfNeededConnect, id } = this.props
    loadQuoteIfNeededConnect(id)
  }

If I comment that out and attempt to use the code below, the store does not update:

  static async getInitialProps({ store, query: { id } }) {
    // this fetches the data, but store is not updated
    await store.dispatch(loadQuoteIfNeeded(id))
    return { id }
  }

I’ve got a console.log directly above the return statement in my reducer, and I can see in my terminal that the data is in fact being fetched and returned properly with the code from getInitialProps(), but the store is not updating.

Any ideas?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:35 (15 by maintainers)

github_iconTop GitHub Comments

7reactions
jabacchettacommented, Dec 6, 2017

In my case it turns out I wasn’t returning the promise in my chain of dispatch functions. Working perfectly now!

For anyone else running into the same problem, here’s an example:

Component — using async/await

static async getInitialProps({ store, query: { id } }) {
    await store.dispatch(loadQuoteIfNeeded(id))
    return { id }
 }

Actions — note that loadQuoteIfNeeded() has an implicit return and getQuote() is being returned

export const initiateLoadQuote = quoteId => (dispatch) => {
  dispatch(loadQuote(quoteId))

  return getQuote(quoteId)
    .then(({ data: quotes }) => {
      if (quotes === null) Router.push('/')
      dispatch(loadQuoteSuccess(quotes, quoteId))
    })
    .catch((err) => {
      dispatch(loadQuoteError(quoteId))
      logAjaxError('initiateLoadQuote', err)
    })
}

export const loadQuoteIfNeeded = quoteId => (dispatch, getState) => (
  shouldLoadQuote(getState(), quoteId) ? dispatch(initiateLoadQuote(quoteId)) : null
)
3reactions
brunoqscommented, Mar 20, 2020

I have same issue, im using nextjs + redux toolkit I got the updated store on server, but i didnt get the store on client up to date like on server

static async  getInitialProps(ctx) {
   if (ctx.isServer) {
     if (ctx.store.getState().users.categories.length === 0) {
        const res = await ctx.store.dispatch(users.usersSlice.actions.getCategories());
        console.log(ctx.store.getState());
        // that console.log return the new state of redux server store
      }
    } else {
      console.log('ctx', ctx.store.getState());
    }
    return {}
  }

Action

getCategories: () => async dispatch => {
    dispatch(categoriesReset());
    try {
      dispatch(signupLoading());
      const res = await axios.get(`/api/v1/users/categories`);
      dispatch(categoriesSucces(res.data));
      return res.data;
    } catch (err) {
      dispatch(categoriesError(err.response.data));
      return err;
    }
  }

Store

import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import rootReducers from "./rootReducers";
const initStoreSSR = {
  users: {
    data: {},
    status: 0,
    token: "",
    message: '',
    categories: []
  }
};
export const initStore = (preloadedState = {}) => {
  return configureStore({
    reducer: rootReducers,
    preloadedState: { ...preloadedState, ...initStoreSSR },
    middleware: [...getDefaultMiddleware()]
  });
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Next-Redux-Wrapper not updating SSR Store - Stack Overflow
I'm working on an app that uses SSR. It is based on React, Next, and Redux. I understand the general concept of having...
Read more >
Why Redux Store Changes Don't Re-render - YouTube
When using Redux, it's common to run into issues where your store isn't updating, or isn't updating in the way you expect it...
Read more >
Server Rendering - Redux - JS.ORG
On the client side, a new Redux store will be created and initialized with the state provided from the server. Redux's only job...
Read more >
React State Not Updating Immediately? - Nate Gage - Medium
React State Not Updating Immediately? I'm setting state in my app and referencing it. Why don't I see the new values?
Read more >
How to use Redux in Next.js - LogRocket Blog
Now we have successfully set up our Redux store. You can verify it by clicking the button, which will dispatch actions based on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found