Adding Redux to your React project

Installation

Add the necessary modules

yarn add react-redux
yarn add redux

Fix the component

import {connect} from 'react-redux';

// definition of DummyComponent here...
const mapStateToProps = (state) => ({
    count: state.count 
});
export default connect(mapStateToProps)(DummyComponent);

Create a DemoService class

import {createStore} from "redux";

const initialState = {
    value: 42,
    status: "Unknown",
    make: "Unknown"
  }
  
  /**
   * The reducer is the only function that modifies the state
   */
  function reducer(state = initialState, action) {
    // console.log(action);
    switch (action.type) {
      case "decrement":
        /* reurn the complete state after action! */
        return {
          ...state, /* previous state */
          value: state.value - 1,
          status: (state.value+1) > 45 ? "HOT" : "COOL"
        }
        break;
      case "increment":
        return {
          ...state,
          value: state.value + 1,
          status: (state.value+1) > 45 ? "HOT" : "COOL"
        }
        break;
      case "set_make":
        return {
          ...state,
          make: action.make
        }
        break;
    }
    return state;
  }

  class DemoService {
      
  }

  DemoService.STORE = createStore(reducer);

  export default DemoService;

Use the DemoService in the App class

import Component1 from './Component1';
import Component2 from './Component2';
import {Provider} from 'react-redux';
import DemoService from './DemoService';

const store = DemoService.STORE;

function App() {
  return (
    <Provider store={store}>
      <Component1></Component1>
      <Component2></Component2>
    </Provider>
  );
}

The component changes state using this.props.dispatch

decrement() {
    this.props.dispatch({ type: "decrement" });
}

increment() {
    this.props.dispatch({ type: "increment" });
}

render() {
    return (<div>
        <h1>Value is {this.props.value} </h1>
        <button onClick={this.decrement.bind(this)}>-</button>
        <button onClick={this.increment.bind(this)}>+</button>
    </div>);
}
When the store is connected, you get the dispatcher in the props. So whenever you want to change the state, call the dispatcher with an action. You can add arguments to thie object too.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.