Skip to content

Instantly share code, notes, and snippets.

@AD0791
Created September 25, 2021 22:09
Show Gist options
  • Save AD0791/a7931ede4cae611238ea6f4aba178749 to your computer and use it in GitHub Desktop.
Save AD0791/a7931ede4cae611238ea6f4aba178749 to your computer and use it in GitHub Desktop.
Redux simplification
/*
applyMiddleware
This method will take a bunch of middlewares and return an enhancer. And enhancers go into the createStore function call.
*/
import { applyMiddleware, createStore } from 'redux'
const logger = (store) => (next) => (action) => {
console.log("DISPATCHED ACTION: ", action);
next(action);
}
const store = createStore(rootReducer, applyMiddleware(logger));
/*
bindActionCreators takes two arguments:
An object with all the action creators inside it.
The method we want to bind our action creators to.
It returns an object, which looks identical to the first argument we passed in. The only difference is, now we can call those methods directly, without calling dispatch explicitly.
*/
const actions = bindActionCreators({ add, increment }, store.dispatch)
actions.increment()
actions.add(4)
/*
When you're developing a huge app where you can segregate data, it makes sense to have multiple reducers to reduce complexity. This method will combine all those multiple small reducers and return one reducer, generally called as root reducer, that our createStore method can use.
*/
import { combineReducers, createStore } from "redux";
// constants
const CHANGE_USER_EMAIL = "CHANGE_USER_EMAIL";
const ADD_PRODUCT = "ADD_PRODUCT";
// action creators
const changeUserEmail = (email) => ({
type: CHANGE_USER_EMAIL,
payload: { email }
});
const addProduct = (product) => ({
type: ADD_PRODUCT,
payload: { product }
});
const initialState = {
user: {
name: "Mark",
email: "mark@facebook.com"
},
cart: {
products: []
}
};
const userReducer = (user = initialState.user, action) => {
if (action.type === CHANGE_USER_EMAIL) {
return {
...user,
email: action.payload.email
};
}
return user;
};
const cartReducer = (cart = initialState.cart, action) => {
if (action.type === ADD_PRODUCT) {
return {
...cart,
products: [...cart.products, action.payload.product]
};
}
return cart;
};
const rootReducer = combineReducers({
user: userReducer,
cart: cartReducer
});
const store = createStore(rootReducer);
console.log(store.getState());
// { user: { name: 'Mark', email: 'mark@facebook.com' }, cart: { products: [] } }
store.dispatch(changeUserEmail("mark@instagram.com"));
console.log(store.getState());
// { user: { name: 'Mark', email: 'mark@instagram.com' }, cart: { products: [] } }
/*
This method doesn't even have anything to do with Redux. The purpose of this method is to bundle multiple functions into one.
*/
const double = (num) => num * 2;
const square = (num) => num * num;
const half = (num) => num / 2;
const halfSquareDouble = (num) => half(square(double(num)));
console.log(halfSquareDouble(2)); // 8
import { compose } from "redux";
const double = (num) => num * 2;
const square = (num) => num * num;
const half = (num) => num / 2;
const halfSquareDouble = compose(half, square, double);
console.log(halfSquareDouble(2)); // 8
/*
This methods creates the Redux store. It takes one mandatory argument reducer, and two optional arguments - preloadedState(also know as initialState) and enhancer.
*/
const reducer = (state, action) => {
return state
}
import { createStore } from 'redux'
const reducer = (state, action) => {
return state
}
const initialState = { value: 0 }
const store = createStore(reducer, initialState)
/*
Middlewares provide us with the ability to intercept actions and do something we want to before that action reaches the reducers. We can log actions, log store state, log crash reports, etc.
Let's create a middleware for logging actions when they get dispatched.
*/
const logger = (store) => (next) => (action) => {
console.log("DISPATCHED ACTION: ", action);
next(action);
}
/*
- replaceReducer: This method is used for replacing the current root reducer function with a new one. Calling this method will change the internal reducer function reference. This comes into play, when you're splitting your code for performance.
*/
const newRootReducer = combineReducers({
existingSlice: existingSliceReducer,
newSlice: newSliceReducer
});
store.replaceReducer(newRootReducer);
/*
- getState: This method is used to get the state of your app.
- subscribe: This method is used for subscribing to the changes on our store. Pass a function to this method and it will get called anytime state changes.
- dispatch: This method is used for dispatching actions. Actions go inside reducers with the current state of your app and might update the state.
*/
import { createStore } from "redux";
const initialState = { value: 0 };
const incrementAction = {
type: "INCREMENT"
};
const reducer = (state = initialState, action) => {
if (action.type === "INCREMENT") {
return { value: state.value + 1 };
}
return state;
};
const store = createStore(reducer);
console.log(store.getState()); // { value: 0 }
store.dispatch(incrementAction);
console.log(store.getState()); // { value: 1 }
////////////////////////////////
import { createStore } from "redux";
const initialState = { value: 0 };
const incrementAction = {
type: "INCREMENT"
};
const addAction = {
type: "ADD",
payload: 5,
}
const reducer = (state = initialState, action) => {
if (action.type === "INCREMENT") {
return { value: state.value + 1 };
}
if (action.type === "ADD") {
return { value: state.value + action.payload }
}
return state;
};
const store = createStore(reducer);
store.dispatch(addAction)
console.log(store.getState()) // { value: 5 }
////////
const add = (number) => {
return {
type: "ADD",
payload: number
}
}
store.dispatch(add(5))
store.dispatch(add(10))
store.dispatch(add(100))
///////////////
import { createStore } from "redux";
const initialState = { value: 0 };
// constants
const INCREMENT = "INCREMENT";
const ADD = "ADD";
// action creators
const increment = () => ({ type: INCREMENT });
const add = (number) => ({ type: ADD, payload: number });
const reducer = (state = initialState, action) => {
if (action.type === INCREMENT) {
return { value: state.value + 1 };
}
if (action.type === ADD) {
return { value: state.value + action.payload };
}
return state;
};
const store = createStore(reducer);
console.log(store.getState()); // { value: 0 }
store.dispatch(increment());
store.dispatch(add(2));
console.log(store.getState()); // { value: 3 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment