javascriptreactjsreduxredux-saga

React.js: Unable to to get the updated state back in App using redux-saga


In the app => Working Demo the redux-saga is getting executed, but I'm unable to get the updated state back in my App component. I'm unable to identify why this application is having this behavior.

productReducer.js

import { FETCH_PRODUCTS_SUCCESS } from "../types/action";

const initialState = {
  products: []
};

export const productsReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_PRODUCTS_SUCCESS:
      state.products = action.products;
      break;
    default:
    // do nothing
  }
};

Solution

  • Mutate states should be avoided. We must update the state immutably. See Reducers and Immutable Updates

    In order to update values immutably, your code must make copies of existing objects/arrays, and then modify the copies.

    import { FETCH_PRODUCTS_SUCCESS } from '../types/action';
    
    const initialState = {
        products: [],
    };
    
    export const productsReducer = (state = initialState, action) => {
        switch (action.type) {
            case FETCH_PRODUCTS_SUCCESS:
                // state.products = action.products
                return { ...state, products: action.products };
            default:
                return state;
        }
    };
    

    codesandbox