mardi 20 octobre 2020

Working with multiple checkbox and hooks on React

I have a multiple checkbox modal that filters a list to show the user, so when i click on one of the checkbox and submit it, the list is filtered to show only the results that match the state that was chosen; this is working just fine, but for some reason when i filter and go back to the modal to choose another option, i don't have that previous one selected (which i should) and also i need to uncheck every selection so i can show the original list (without any filtering) again.

This is my results array:

messages=[
{id:1, description:'abc', status:'SENT'},
{id:2, description:'hello', status:'CANCELLED'},
{id:1, description:'bye', status:'SENT'}];

This is my states array:

const states = [
    {
      id: 1,
      label: "SENT",
      class: "checkbox",
    },
    { id: 2, label: "CANCELLED", class: "checkbox" },
    { id: 3, label: "EMITING", class: "checkbox" },
    {
      id: 4,
      label: "NULLED",
      class: "checkbox",
    },
    
  ];

This is my checkbox component:

const filterOptions = states.map((option) => (
    <div key={option.label} className="mb-3">
      <Form.Check
        type={option.class}
        id={option.id}
        name={option.label}
        label={option.label}
        onChange={filterState}
      />
    </div>
  ));

This is my filterState function:

let items = [];
  const filterState = (event) => {
    const target = event.target;
    const value = target.name;

    if (target.checked) {
      items.push(value);
    } else {
      items.splice(value, 1);
    }
  };

The items array now has only the labels of the checkbox that are checked so i can use it to filter the results on Submit:

const onSubmit = () => {
    event.preventDefault();
    event.stopPropagation();
    let search = filterMessagesByStatus(items);
    if (search.length > 0) {
      setData(search);
      setIsActive(true);
      setEmptySearch(false);
    } else {
      setIsActive(false);
      setEmptySearch(true);
    }

    setModalShowFilters(false);
  };

Now i don't know why is not saving the checkbox that i choose before, and also i don't know what is the best way to return the list to it's original state (without filtering, unchecking everything).

Can anyone help me with this?




Aucun commentaire:

Enregistrer un commentaire