How would you implement createStore function from Redux?
@Yomesh Gupta

JavaScriptIntermediate
2449
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

Redux is a very popular state management library and it is used as a de-facto standard in millions of projects out in the real world applications. Usage typical looks like the following

import { createStore } from 'redux';

const rootReducer = (state = {}, action) => {
  switch(action.type) {
    case 'ADD_USER':
      return {
        ...state,
        user: action.payload
      };
    default:
      return state;
  };
};

const initialState = {};

const store = createStore(rootReducer, initialState);

Demo:

Now, createStore returns an object that exposes many methods but we want you to focus on primarily three: getState, subscribe, and dispatch. Your problem statement is to create your copy of createStore that takes reducer and initialState as arguments and behaves exactly like createStore from redux.

import { createStore } from 'customRedux';

const rootReducer = (state = {}, action) => {
  switch(action.type) {
    case 'ADD_USER':
      return {
        ...state,
        user: action.payload
      };
    default:
      return state;
  };
};

const initialState = {};

const store = createStore(rootReducer, initialState);

store.subscribe(() => {
  console.log("Listener called");
});

console.log(store.getState()); // {}

store.dispatch({
  type: 'ADD_USER',
  payload: {
    id: 1,
    name: 'Yomesh Gupta'
  }
});

/**
  Listener called
   { user: { id: 1, name: 'Yomesh Gupta' } }
**/
console.log(store.getState());

You need to add the validations too.

Loading IDE...