user9777330
user9777330

Reputation: 35

React component won't re-render after state change in Redux

So I have a reducer with several different cases. All of the other cases (ADD_VEHICLE, UPDATE_VEHICLE, etc) work just fine, but DELETE_VEHICLE will not re-render after the state has been updated. As you can see, I am simply removing an item from an array with splice(). I've confirmed that it is removing the item with console logs, but it still won't refresh like add and update. What's stranger is that if I make it so that I assign anything else to the vehicles property inside the object, it will render that just fine. However, it refuses to render it when I try to set it to the current state.vehicles.

Things I have tried:

No matter what I do, it will not re-render the list without the deleted item. And if it matters, I have confirmed that the item is being deleted in the database.

My reducer:

function vehicleTableReducer (state = {}, action) {
    switch (action.type) {
        case REQUEST_VEHICLES:
            return state
        case RECEIVE_VEHICLES:
            return Object.assign({}, state, { vehicles : action.vehicles })
        case ADD_VEHICLE:
            state.vehicles.push(action.vehicle)
            return Object.assign({}, state, { tableState : action.tableState })
        case DELETE_VEHICLE:
            var v = state.vehicles.find(v => v.id == action.vehicle.id)
            var index = state.vehicles.indexOf(v)
            state.vehicles.splice(index, 1)
            return Object.assign({}, state, { vehicles : state.vehicles })
        case UPDATE_VEHICLE:
            var v = state.vehicles.find(v => v.id == action.vehicle.id)
            var index = state.vehicles.indexOf(v)
            state.vehicles[index] = action.vehicle
            return Object.assign({}, state, { vehicles : state.vehicles })
        case TOGGLE_TABLE_STATE:
            return Object.assign({}, state, { vehicles : state.vehicles, tableState : action.tableState })
        default:
            return state;
    }
}

Upvotes: 1

Views: 176

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

Try simply filter out unnecessary element:

case DELETE_VEHICLE:
   var newVehicles = state.vehicles.filter(v => v.id !== action.vehicle.id)
   return Object.assign({}, state, { vehicles : newVehicles })

It seems that you don't really remove that element in your code.

Upvotes: 1

Related Questions