lost9123193
lost9123193

Reputation: 11040

Adding and Removing Data from/to State in Redux/React using Lodash

I have a table with check boxes. When a user selects a check box, the id is sent to an action creator.

Component.js

handlePersonSelect({ id }, event) {
   const { selectPerson, deselectPerson } = this.props;
   event.target.checked ? selectPerson(id) : deselectPerson(id);
}

action.js

export function selectPerson(id) {
  console.log("selected")
  return {
    type: SELECT_PERSON,
     payload: id
  };
}

export function deselectPerson(id) {
  return {
    type: DESELECT_PERSON,
     payload: id
  };
}

I'm able to go all the way up to this step, at which I'm lost: This is the offending code:

import { 
  SELECT_PERSON,
  DESELECT_PERSON,
  FETCH_PEOPLE
} from '../actions/types';


const INITIAL_STATE = {  people:[], selectedPeople:[]};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_PEOPLE:
        return {...state, people: action.payload.data};
    case SELECT_PERSON:
      return [action.payload, ...state ]; 
    case DESELECT_PERSON:
      return _.without({state, selectedPeople:action.payload});
  }
  return state;
}

The selectedPeople state should add/subtract the id's based on each case. As of now, everytime I deselect the id, my whole "people" table disappears.

Upvotes: 0

Views: 770

Answers (1)

DDS
DDS

Reputation: 4375

You should return the complete state from the reducer in all cases, so:

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_PEOPLE:
      return {...state, people: action.payload.data};
    case SELECT_PERSON:
      return {...state, selectedPeople: [ ...state.selectedPeople, action.payload]}; 
    case DESELECT_PERSON:
      return {...state, selectedPeople: _.without(state.selectedPeople, action.payload)}; 
    default
      return state;
  }
}

Also note you didn't have a DESELECT_PERSON action, but instead 2 SELECT_PERSON actions. Possibly a typo.

Upvotes: 1

Related Questions