Home > Software design >  How to update an item in a redux state?
How to update an item in a redux state?

Time:12-20

I have a redux reducer defined like below

const initialState = {
    loading: false,
    data: {radInfo: [], geoInfo: [], latInfo: []}
}


const downloadReportReducer = (state=initialState, action) => {
    const {type, payload} = action
    switch(type) {
        case "LOADING_REPORT":
            return {
                ...state,
                loading: true
            }
        case "CREATING_REPORT":
            return {
                ...state,
                loading: true,
            }
        default:
            return state
    }
}

Now I call an API and call the reducer accordingly. This is how I do it

dispatch({
          type: "CREATING_REPORT",
          payload: {
              data: {"geoInfo": {"code": 1, "loc": "MUN", "freq": [12, 1, 22]}}
          }
})

As you can see in payload data, the key is called geoInfo and I want this key to be matched against the one in the reducer and the value get appended to it.

So my updated reducer state should look like

{
        loading: true,
        data: {radInfo: [], geoInfo: [{"code": 1, "loc": "MUN", "freq": [12, 1, 22]}], latInfo: []}
}

I tried the following but it didn't work

case "CREATING_REPORT":
    return {
                ...state,
                loading: true,
                radInfo: payload.data.radInfo? state.data.radInfo.push(payload.data.radInfo): {},
                geoInfo: payload.data.geoInfo? state.data.geoInfo.push(payload.data.geoInfo): {},
                latInfo: payload.data.latInfo? state.data.latInfo.push(payload.data.latInfo): {} 
    }

How do update my redux state?

CodePudding user response:

You just have a few logical issues with your reducer. Your Info states live within the data key. If they are provided, you'll want to make a shallow copy of the previous state and add the new state onto that shallow copy.

case "CREATING_REPORT":
  return {
    ...state,
    loading: true,
    data: {
      radInfo: payload.data.radInfo
        ? [...state.data.radInfo, payload.data.radInfo]
        : state.data.radInfo,
      geoInfo: payload.data.geoInfo
        ? [...state.data.geoInfo, payload.data.geoInfo]
        : state.data.geoInfo,
      latInfo: payload.data.latInfo
        ? [...state.data.latInfo, payload.data.latInfo]
        : state.data.latInfo,
    },
};
  • Related