Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { createStore, combineReducers, applyMiddleware } from 'redux';
- const initialState = {
- loading: false,
- list: []
- };
- const userReducer = (state = initialState, action) => {
- switch(action.type) {
- case 'ADD_USER': {
- const list = [...state.list];
- list.push(action.user)
- return { ...state, list };
- }
- case 'FETCH': {
- return { ...state, loading: true };
- }
- default: {
- return state;
- }
- }
- };
- const initialStateProducts = {
- loading: false,
- list: []
- };
- const productsReducer = (state = initialStateProducts, action) => {
- switch(action.type) {
- case 'ADD_PRODUCT': {
- const list = [...state.list];
- list.push(action.product);
- return { ...state, list };
- }
- case 'FETCH': {
- return { ...state, loading: true };
- }
- default: {
- return state;
- }
- }
- };
- const reducers = combineReducers({
- users: userReducer,
- products: productsReducer
- });
- const logger = store => next => action => {
- console.log(action.type, "Fired!!");
- next(action);
- }
- const arrayMiddleware = store => next => action => {
- if(Array.isArray(action)) {
- return action.map(ac => store.dispatch(ac));
- }
- return next(action);
- }
- const fnMiddleware = store => next => action => {
- if(typeof action === "function") {
- return action(store.getState(), store.dispatch);
- }
- return next(action);
- }
- const middlewares = applyMiddleware(fnMiddleware, arrayMiddleware, logger);
- const store = createStore(reducers, middlewares);
- store.subscribe(() => {
- console.log("State changed", store.getState());
- });
- const addUser = (user) => {
- return {
- type: 'ADD_USER',
- user
- }
- };
- store.dispatch(addUser({name: 'ABCD', email: 'some_mail@email.com'}));
- store.dispatch({ type: 'ADD_PRODUCT', product: {name: 'Apple', qty: 10} });
- store.dispatch({ type: 'FETCH' });
- store.dispatch([
- { type: 'ADD_USER', user: { name: 'ABCD1', email: 'some_mail@email.com' } },
- { type: 'ADD_USER', user: { name: 'ABCD1', email: 'some_mail@email.com' } },
- { type: 'ADD_PRODUCT', product: { name: 'someproduct', qty: 10 } },
- { type: 'ADD_PRODUCT', product: { name: 'someproduct', qty: 10 } },
- { type: 'ADD_PRODUCT', product: { name: 'someproduct', qty: 10 } },
- ]);
- store.dispatch(function(state, dispatch) {
- console.log(state);
- console.log("Waiting for API response");
- setTimeout(() => {
- console.log("API responded");
- dispatch({ type: 'ADD_PRODUCT', product: { name: 'someproduct', qty: 10 } })
- }, 1000);
- });
Add Comment
Please, Sign In to add comment