Home > other >  update multiple objects in state with single function
update multiple objects in state with single function

Time:11-19

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:

CodePudding user response:

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);

CodePudding user response:

make the key field dynamic like this

const setValue = (key:string, value:string) => {
       setAccordionOpen((previousState) => ({
                ...previousState,
                [key]: value,
              }))
}

call like this

setValue( 'schoolAccordion', !accordionOpen.schoolAccordion)
  • Related