UVic
UVic

Reputation: 1801

Setting the initial state using next react redux wrapper

I am using next react-redux package. How to set the initial state ?. The documentation only states that withRedux function only accepts a makeStore function as argument. Setting a default value of initial state in makeStore function doesn't work.

import {createStore} from "redux";
import rootReducer from './reducers';

/**
* @param {object} initialState
* @param {boolean} options.isServer indicates whether it is a server side or client side
* @param {Request} options.req NodeJS Request object (not set when client applies initialState from server)
* @param {Request} options.res NodeJS Request object (not set when client applies initialState from server)
* @param {boolean} options.debug User-defined debug mode param
* @param {string} options.storeKey This key will be used to preserve store in global namespace for safe HMR 
*/
const makeStore = (initialState={hello: "world"}, options) => {
    return createStore(rootReducer, initialState);
};

export default makeStore;
import { combineReducers } from 'redux';
import sessionReducer from './session';
import userReducer from './user';

const rootReducer = combineReducers({
  sessionState: sessionReducer,
  userState: userReducer,
});

export default rootReducer;

Upvotes: 2

Views: 2932

Answers (1)

Blundering Philosopher
Blundering Philosopher

Reputation: 6805

I'd recommend setting the initial state in your individual reducers, not in your createStore function. Try setting your initial state in the individual reducers themselves, like this:

// auth reducer
import * as actionTypes from '../actions/actionTypes';

// INITIAL STATE!
const initState = {
    authError: null,
};

// PASS INITIAL STATE INTO YOUR REDUCER!
const authReducer = (state = initState, action) => {
    switch(action.type) {
        // example actionType
        case actionTypes.LOGIN_SUCCESS: return {...state, authError: null };
        case actionTypes.LOGIN_ERROR: return {...state, authError: 'oops, error!' };
    default: return state;
}

export default authReducer;

I'm assuming your rootReducer is just combining other reducers, like this:

// example root reducer
import authReducer from './authReducer';
import projectReducer from './projectReducer';
import { combineReducers } from 'redux';

const rootReducer = combineReducers({
    auth: authReducer,
    project: projectReducer,
});

export default rootReducer;

Upvotes: 2

Related Questions