- 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"})
Easy to learn: https://www.kirupa.com/react/introduction_to_redux.htm
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.
No comments:
Post a Comment