What is the best practice to remove duplicate items from an array in a reducer?

Viewed 696

I am new to working with reducers to store data and have stumbled across an issue. I currently have a list of checkboxes that when clicked dispatches an action to store them inside an array in my reducer. Currently, however, I can keep checking/unchecking and the same value will continue to be pushed to the array.

How can I prevent this from happening? Do I somehow filter out inside the reducer or in my handleChange event on the checkbox?

I have added a small snippet of my current code

Thanks!

function handleCheckboxChange(e) {
    if (e.target.checked) {
      checkboxContext.dispatch({
        type: 'SET_PROPERTY_TYPE',
        payload: { [e.target.name]: e.target.checked }
      });
    }
  }
  
  
 const FilterCheckbox = ({ name, value, handleChange, checkedItems }) => (
  <Label>
    <FilterInput
      type="checkbox"
      name={name}
      value={value}
      onChange={handleChange}
      checked={checkedItems[name]}
    />
    {name}
  </Label>
);

export default FilterCheckbox;

// Sets the selected value...
 case 'SET_PROPERTY_TYPE':
      return {
        ...state,
        propertyType: [...state.propertyType, action.payload]
      };

1 Answers

Yes you could just filter your state.propertyType to remove any duplicates.

// Sets the selected value...
 case 'SET_PROPERTY_TYPE':
      return {
        ...state,
        propertyType: [
            ...state.propertyType.filter((value) => 
                 Object.keys(value)[0] !== Object.keys(action.payload)[0]), 
            action.payload
        ]
      };

You could also change your state.propertyType to an object to make things nicer:

  function handleCheckboxChange(e) {
    checkboxContext.dispatch({
      type: 'SET_PROPERTY_TYPE',
      payload: { [e.target.name]: e.target.checked }
    });
  }


 const FilterCheckbox = ({ name, value, handleChange, checkedItems }) => (
  <Label>
    <FilterInput
      type="checkbox"
      name={name}
      value={value}
      onChange={handleChange}
      checked={checkedItems[name]}
    />
    {name}
  </Label>
);

export default FilterCheckbox;

// Sets the selected value...
 case 'SET_PROPERTY_TYPE':
      return {
        ...state,
        propertyType: {
          ...state.propertyType, 
          ...action.payload
        }
      };

You would also need to change how FilterCheckbox are mapped from the state.

Related