0

I am using Switch Material UI Component to filter the between the tasks completed and not completed in my list.

See the demo codesandbox

I can switch the elements completed but the problem is that i can not switch back to the not completed when i toggle ( i can not reuse my entire tasks array to filter )

The method

  const getCompleted = (e, value) => {
    let result = [];
    result = tasks.filter(({ completed }) => completed);
    setFilteredData(result);
    console.log(result);
  };

The component

  <FormControl component="fieldset">
    <FormControlLabel
      value="start"
      control={<Switch onChange={getCompleted} color="primary" />}
      label="Start"
      labelPlacement="start"
    />
  </FormControl>
Koala7
  • 1,340
  • 7
  • 41
  • 83

3 Answers3

1

You need to handle somehow the checked value of your switch

I don't know if in initial position, you need to show all values, but my answer was based on that senario (not checked then show all tasks, else show only completed)

  const getCompleted = (e, value) => {
    let result = [];
    result = e.target.checked
      ? tasks.filter(({ completed }) => completed)
      : tasks;
    setFilteredData(result);
  };
Apostolos
  • 10,033
  • 5
  • 24
  • 39
1

You don't seem to be filtering based on the value of the switch.

const getCompleted = (e, value) => {
    let result = [];
    let switchValue = e.target.checked;
    result = tasks.filter(({ completed }) => completed === switchValue);
    setFilteredData(result);
    console.log(result);
  };
Squiggs.
  • 4,299
  • 6
  • 49
  • 89
0

You need to check for the toggle value in the function which is called on toggle change.

const getCompleted = (e, value) => {
    let result = [];
    result = value ? tasks.filter(({ completed }) => completed) : tasks;
    setFilteredData(result);
  };

See the updated codesandbox

Khateeb321
  • 1,861
  • 23
  • 25