Showing posts with label redux. Show all posts
Showing posts with label redux. Show all posts

Sunday, May 3, 2020

React Redux Example

Basics:
  • Redux provides means to create an empty store where application state can be manufactured.
  • You tell the store what to create as the application state, how to update the application state thru reducer.
  • Reading from the application state in application is straight forward.
  • Updating the application state is by triggering the update logic in the store by dispatching the actions.
  • NOTE: When you update a state, you don’t update the state but rather create a new state out of old state.
  • react-redux provides couple of additional facilities, Provider and connect.
  • Provider to provide the store to the root component.
  • Connect passes state, dispatch actions to child component. 
Example:
  • npx create-react-app reduxexample
  • cd reduxexample
  • npm install redux
  • npm install react-redux
  • Remove all files under src folder and public folder
  • Create index.html under public folder
  • Create rest of the files under src folder
  • npm start
index.html

index.js

reducer.js

dispatcher.js

kitchen.jsx













Menu.jsx

App.jsx

Thursday, November 10, 2016

React Redux


  • redux provides an empty store where application state can be manufactured.
  • You tell the store what to create as the application state, how to update the application state (thru reducer)
    • store = Redux.createStore(reducer)
  • Reading from the application state in application is straight forward: 
    • store.getState()
  • Updating the application state is by triggering the update logic in the store by dispatching the actions.
    • store.dispatch({type: 'increase', graceMarks: 5})
  • NOTE: When you update a state, you don’t update the state but rather create a new state out of old state.
  • You can even subscribe to store to get the status on the updates.
    • state.subscribe(state.getState())
  • react-redux provides couple of additional facilities, Provider and connect.
  • Provider to provide the store to the root component.
  • Connect passes state, dispatch actions to child component. 
A sample using just redux:

// importing createStore from redux
import {createStore} from 'redux';

// Creating a reducer
const sampleReducer = function(state, action){
    if (!state){
         state = 0;
    }
    if (action.type === "INC"){
         state =  state + 1;
    }
    return state;
}

// Create a store. Passing in the reducer that i created above
const store = createStore(sampleReducer);

// subscribing to store to see the updates
store.subscribe(() => {
    console.log("state changed ", store.getState());
})

// start dispatching actions to store.
store.dispatch({type:"INC",payload:"something"})


There you go… You create a reducer, you create a store and then whenever you dispatch actions, the reducer or multiple reducers will act upon on that store.