Ghadir
Ghadir

Reputation: 537

React Redux: update local state with a new value on action dispatch

I have an action that creates a 'supplier' in the database, and when it finishes it calls another action that is supposed to create a supplier locally (through redux).

This is very basic but I am a bit lost on how to add the new supplier to the already existing supplier state.

Here is the action (The newly created supplier is passed to it):

export const createSup = (sup) => {
  return {
      type: "CREATE_SUP",
      sup,
  };
};

Here is my reducer file along with the error line (Everything working fine except for the CREATE_SUP case):

const initialState = {
  value : {},
  loaded: false,
  error: false
}

const supReducer = (state = initialState, action) => {
    switch (action.type) {
      case 'LOAD_SUPPLIERS': 
      return {
        value: action.sups,
        loaded: false,   //this might need to be set to true
        error: false
      }
      case 'LOAD_SUPPLIERS_ERROR': 
        console.log("load suppliers error")
        return {
          ...state,
          loaded: false,   
          error: true
        }
      case 'LOAD_SUPPLIERS_SUCCESS': 
        return {
          ...state,
          loaded: true,   
          error: false
        }
      case 'CREATE_SUP':
        return {
          value: {...state.value, action.sup}, //************ERROR *************//
          loaded: true,   
          error: false
        }
      default:
        return state;
    }
  };

  export default supReducer;

It gives me an error mark under action.sup (I guess it expects only one value). Should I not worry about returning the old value of the state, and just return the new supplier? (I think I am missing a point or two on how exactly reducers work).

Thank you for any help.

Upvotes: 0

Views: 72

Answers (1)

brianyates
brianyates

Reputation: 399

My guess would be that you meant to use the spread operator, like so:

  case 'CREATE_SUP':
    return {
      value: { ...state.value, ...action.sup }, 
      loaded: true,   
      error: false
    }

action.sup isn't an object property, it's an object. I assume you just want to apply those properties to your state object.

I should also note that your reducer should typically always return a state object in the same "shape" for every action. So if your initial state object is { prop1: 1, prop2: 2, prop3: 3 }, it should always return something similar to that, just with different values. I say this because it looks like your "LOAD_SUPPLIERS" action is kinda doing its own thing and not copying the current state. Just remember that your state object is meant to be accessed "globally" (I use this term loosely) with Redux. The components that use your Redux state will expect a certain object shape and certain properties to always be there, so you need to make sure you always return that with your reducer. Hope that makes sense.

Upvotes: 1

Related Questions