Helder Esteves
Helder Esteves

Reputation: 469

Populating initialState in reducer through localStorage

I have a react/redux app where I need to populate a prop from state initially with localStorage.

I was thinking of doing it with something like this

const initialState = (() => {
  let username = window.localStorage.getItem('username');
  if (!username) {
    username = '';
  }
  return {
    username: username
  };
})();

I heard that it's not really a good practice to complicate the initialState with logic, but I haven't found any other ways of doing it

Is there a cleaner workaround?

Upvotes: 3

Views: 797

Answers (1)

Hemant Parashar
Hemant Parashar

Reputation: 3774

You can just use default function parameters to define the initial state in the reducer itself like this with simply an or operator. The initial state for user will be first checked in the local storage and if it's null then it'll be an empty string.

const userReducer = ( state = window.localStorage.getItem("username") || "", action ) => {
  /*
   * some logic to handle actions
   *
   */
  return state;
};

Hope this helps !

Upvotes: 2

Related Questions