import { useState, useEffect, useCallback } from "react";
const useToggleOpen = <T extends object = AnyTypeObject>(list: T[]) => {
const [data, setData] = useState(list);
useEffect(() => {
setData(list);
}, [list]);
const toggleOpen = useCallback(
(index: number, key: string, e: Event) => {
const newData = data.map((item: any, itemIndex) => {
const isOpen =
item[`${key}IsOpen`] !== undefined ? !item[`${key}IsOpen`] : true;
return {
...item,
[`${key}IsOpen`]: itemIndex === index ? isOpen : item[`${key}IsOpen`],
};
});
e.preventDefault();
e.stopPropagation();
setData(newData);
},
[data]
);
return [data, toggleOpen] as const;
};
export default useToggleOpen;