redux library code example
Example 1: redux
Redux is a state management library
1 Create Initial State
2 Define Action Types
3 Define Action Creators
4 Create Reducers
5 Change the initial State
6 Pass the parameters to the Creator function and the reducers
Code
const initialState = {
todos: [
{
text: "eat food",
},
{
text: "Exercise",
},
],
};
const ADD_TODO = "ADD_TODO";
function addTodo(text) {
return {
type: ADD_TODO,
payload: text,
};
}
function todoReducer(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [...state.todos, { text: action.payload }];
default:
return state;
}
}
console.log("Initial State : ", initialState);
const action = addTodo("Make it work");
const newState = todoReducer(initialState, action);
console.log(newState);
Example 2: Redux
npm install redux
export const SET_USER = 'SET_USER'
export const setUser = user => {
return {
type : SET_USER,
payload : {
currentUser : user
}
}
const user_reducer = (state=intialState,action)=>{
switch(action.type){
case SET_USER :
return {
currentUser : action.payload.currentUser
}
}