Monday, 17 October 2022

How can I aggregate several states into one master state with react hook?

I apologize if I didn't phrase the question correctly so let me explain.

I have a reusable Filter component that generates checkboxes or radio buttons depending on a predetermined list.

For example, the lists below will generate each a Filter component with that many checkboxes and labels

const genre = ["Action", "Horror", "Comedy", "Drama"];
const contenttype = ["Series", "Movies", "Documentaries"];
const dategranularity = ["All Time", "Yearly", "Monthly", "Weekly"];

like so

<Filter data={genre} label="Genre" checkboxgroup />
<Filter data={contenttype} label="Content Type" checkboxgroup />
<Filter data={dategranularity} label="Date Granularity" defaultValue="all time" />

Here's the Filter component function I am using for my goal (reduced for brevity)

const Filter = ({ data, label, checkboxgroup, defaultValue }) => {

  const [checkedState, setCheckedState] = useState([]);
  const [radios, setRadios] = useState([]);
  const [values, setValues] = useState([]);

  const handleList = (e) => {
    const updatedValuesState = values.includes(e.target.name)
      ? values.filter((label) => label !== e.target.name)
      : [...values, e.target.name];
    setValues(updatedValuesState);
    setActive(updatedValuesState.length === data.length);
  };
};

At the moment I able to capture and aggregate the checkboxes that are checked ONLY within its own Filter component So for example if I clicked on action and horror, I get values: ['action', 'horror'] in my console. That's good! But if I click on "series" on the next Filter component, the state is completely rebuilt and it console logs values: ['series'].

My end goal is to show values: ['action', 'horror', 'series'] even the radio button value can be aggregated but only once. as opposed to checkboxes can be multiple.

Here's a sandbox with all you need in place to mess with it. Thanks!!!



from How can I aggregate several states into one master state with react hook?

No comments:

Post a Comment