Practical React - Part 3 Working With Redux (State Management)

React JS

Install the redux package:

npm i --save react-redux

Create a store instance, some reducer and reducer composer:

store.js


import { createStore } from 'redux'

import RootReducer from './root-reducer'

const store = createStore(RootReducer);

export default store;

root-reducer.js

import { combineReducers } from 'redux'
import LoginState from './login-state'

const RootReducer = combineReducers({
   LoginState 
})

export default RootReducer

login-state.js


export default function LoginState(state = { isLoggedIn: false, loginTime: null }, action) {

    switch (action.type) {

      case 'LOGGED_IN':
        return new { isLoggedIn: true, loginTime: new Date() };      

      case 'LOGGED_OUT':
        return new { isLoggedIn: false }

      default:
        return state;
    }
}

Wrap the main component:


<Provider store={store}>
    <BrowserRouter>
        <App/>
    </BrowserRouter>
</Provider>

Subscribe to this store instance in any other component:


store.subscribe(() => {
            const loginState = store.getState().LoginState;
            console.dir(loginState);
});

Dispatch an action by calling:


store.dispatch({
           type: 'LOGGED_IN'
});

Post a Comment

Previous Post Next Post