Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update multiple objects in state with single function

I have 3 different Accordions that a single state controls their open and close state like so:

 const [accordionOpen, setAccordionOpen] = useState({
    countryOfOriginAccordion: true,
    schoolAccordion: false,
    areaOfStudyAccordion: false,
  });

ideally, I am setting each state with their own function like this:

setAccordionOpen((previousState) => ({
                ...previousState,
                schoolAccordion: !accordionOpen.schoolAccordion,
              }))

I want to use a single function that changes this value in state dynamically:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do something like this:

const toggleAccordionOpen = (accordionName) => setAccordionOpen((prevState) => ({
  ...prevState,
  [accordionName]: !prevState[accordionName],
}));

// Example of usage
toggleAccordionOpen('countryOfOriginAccordion');

If you are using Typescript you can annotate the accordionName to a type union:

const ACCORDION_NAMES = {
  COUNTRY_OF_ORIGIN: 'countryOfOriginAccordion',
  SCHOOL: 'schoolAccordion',
  AREA_OF_STUDY: 'areaOfStudyAccordion',
} as const;

type AccordionNameGeneric<T> = T[keyof T];
type AccordionName = AccordionNameGeneric<typeof ACCORDION_NAMES>;

const toggleAccordionOpen = (accordionName: AccordionName) => 
...

And then call it like this:

toggleAccordionOpen(ACCORDION_NAMES.COUNTRY_OF_ORIGIN);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading