import {
Box,
Button,
ConfirmModalComponent,
Controller,
getApp,
getMenu,
getRoles,
getUsers,
Grid,
Loading,
ModalComponent,
SelectField,
toast,
useEffect,
useForm,
useMutationRequest,
useQueryRequest,
userAccess,
yupResolver,
} from "@src/imports";
import { AssignMenuFormSchema } from "@src/schema";
import {
OutputUseMutationType,
OutputUseQueryType,
} from "@src/types/generalTypes";
import {
AppDataType,
AssignMenuActions,
AssignMenuActionTypes,
AssignMenuReturnedData,
AssignMenuStateType,
AssignMenuStateTypes,
GetAppType,
GetMenuData,
GetMenuType,
GetMneuServiceParamsType,
GetRolesData,
GetRolesServiceParamsType,
GetUsersData,
GetUserServiceParamsType,
GetUsersType,
ReturnGetRoleType,
UserAccessType,
} from "@src/types/services/assignMenuType";
import { Suspense, useContext, useReducer, useRef, useState } from "react";
import { SelectInstance } from "react-select";
import { InferType } from "yup";
import ItemList from "./MenuList";
import { StatusMessage } from "@src/types/services/commonServicesTypes";
import { ModalDrawerContext } from "@src/context/ModalDrawerContext";
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 600,
height: 500,
bgcolor: "background.paper",
border: "2px solid #000",
boxShadow: 24,
p: 4,
};
type DmutateFn<Tparams, DretunedData> = (
params: Tparams
) => Promise<DretunedData>;
const initialState: AssignMenuStateType = {
roleData: undefined,
userData: undefined,
menuData: undefined,
};
const reducer = (state: AssignMenuStateType, action: AssignMenuActions) => {
switch (action.type) {
case AssignMenuActionTypes.SET_ROLES:
return { ...state, roleData: action.payload };
case AssignMenuActionTypes.SET_USERS:
return { ...state, userData: action.payload };
case AssignMenuActionTypes.SET_MENU:
return { ...state, menuData: action.payload };
default:
return state;
}
};
const AssignMneuForm = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const [open, setOpen] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const handleOpen = () => showMenuListModal()
const handleClose = () => setOpen(false);
const [checkedItems, setCheckedItems] = useState<number[]>([]);
let roleRef = useRef<SelectInstance<GetRolesData>>(null);
let userRef = useRef<SelectInstance<GetUsersData>>(null);
// let menuRef = useRef<SelectInstance<GetMenuData>>(null);
const {
handleSubmit,
control,
setValue,
watch,
getValues,
formState: { errors },
} = useForm({
mode: "onTouched",
resolver: yupResolver(AssignMenuFormSchema),
defaultValues: {
userId: undefined,
menuItems: undefined,
appId: undefined,
roleId: undefined,
},
});
useEffect(() => {
const modifiedMenuItems = checkedItems.map((item) => {
return {
menuID: item,
};
});
setValue("menuItems", modifiedMenuItems);
}, [checkedItems]);
const {
data: getAppIdOptions,
isLoading: getAppIdLoding,
}: OutputUseQueryType<GetAppType> = useQueryRequest({
queryFn: getApp,
queryKey: "get-app-data",
});
const {
mutateAsync: getRolesOptions,
isLoading: getRolesLoding,
}: OutputUseMutationType<GetRolesServiceParamsType, ReturnGetRoleType> =
useMutationRequest(getRoles);
const {
mutateAsync: getUsersOptions,
isLoading: getUsersLoding,
}: OutputUseMutationType<GetUserServiceParamsType, GetUsersType> =
useMutationRequest(getUsers);
const {
mutateAsync: getMenuOptions,
isLoading: getMenuLoding,
}: OutputUseMutationType<GetMneuServiceParamsType, GetMenuType> =
useMutationRequest(getMenu);
const {
mutateAsync: postUserAccess,
isLoading: postUserAccessLoding,
}: OutputUseMutationType<UserAccessType, StatusMessage> =
useMutationRequest(userAccess);
const onSubmit = async (data: InferType<typeof AssignMenuFormSchema>) => {
console.log(data);
const streucturedData = {
userID: data.userId,
menuItems: data.menuItems,
};
console.log(streucturedData);
const responseData = await postUserAccess(streucturedData);
if (responseData && responseData.status) {
console.log(responseData);
toast.success(responseData.message);
setConfirmOpen(false);
}
};
const loadAssignMenuDataHandler = async <
Tparams,
DretunedData extends AssignMenuReturnedData
>(
params: Tparams,
mutateFn: DmutateFn<Tparams, DretunedData>,
type: "user" | "role" | "app"
): Promise<AssignMenuStateTypes> => {
if (type === "app") {
userRef.current!.clearValue();
roleRef.current!.clearValue();
} else if (type === "role") {
userRef.current!.clearValue();
}
try {
const data: DretunedData = await mutateFn(params);
console.log(data, type, " injaaaaa");
return data?.data; // Ensure this matches the expected return type
} catch (error) {
console.error("Error loading data:", error);
throw error; // Rethrow the error if you want to handle it later
}
};
const extractCheckedIds = (items: GetMenuData[]): number[] => {
let exCheckedIds: number[] = [];
items.forEach((item) => {
if (item.checkflag) {
exCheckedIds.push(item.id);
}
if (item.child && item.child.length > 0) {
exCheckedIds = exCheckedIds.concat(extractCheckedIds(item.child));
}
});
return exCheckedIds;
};
useEffect(() => {
// Initialize checkedItems based on items' checkflag
if (state.menuData) {
const extractChecked = extractCheckedIds(state.menuData);
setCheckedItems(extractChecked);
}
}, [state.menuData]);
const { setToggleModal, setModalHeader, setInnerModalJSX } =
useContext(ModalDrawerContext);
const showMenuListModal = () => {
setToggleModal(true);
setModalHeader("لیست دسترسی ها");
setInnerModalJSX(
<Suspense fallback={<Loading />}>
<div>
<ItemList
items={state.menuData && state.menuData}
checkedItems={checkedItems}
setCheckedItems={setCheckedItems}
/>
{/* <CheckboxTree data={state.menuData && state.menuData} /> */}
</div>
<div className="flex justify-end m-1 mt-3">
<Button
variant="contained"
onClick={() => setConfirmOpen(true)}
color="primary"
disabled={postUserAccessLoding}
>
ثبت دسترسی ها
</Button>
</div>
<ConfirmModalComponent
confirmAction={handleSubmit(onSubmit)}
onClose={() => setConfirmOpen(false)}
openModal={confirmOpen}
title="آیا میخواهید تغییرات ثبت شود؟"
/>
</Suspense>
);
};
useEffect(() => {
if(open){
handleOpen()
}
},[open])
return (
<div className="flex flex-col gap-4 w-full">
<form
className="w-full flex flex-col gap-4"
onSubmit={handleSubmit(onSubmit)}
>
<Grid container spacing={1}>
<Grid item xs={12} md={4} lg={3}>
<Controller
name="appId"
control={control}
render={({ field }) => (
<SelectField
isLoading={getAppIdLoding}
{...field}
onChange={async (val: AppDataType) => {
if (!!val && val.appID !== 0) {
field.onChange(val.appID);
const data = await loadAssignMenuDataHandler(
{ params: { _AppID: val.appID } },
getRolesOptions,
"app"
);
dispatch({
type: AssignMenuActionTypes.SET_ROLES,
payload: data as GetRolesData[],
});
}
}}
options={getAppIdOptions && getAppIdOptions?.data}
label="برنامه"
error={errors.appId?.message}
getOptionLabel={(option: AppDataType) =>
option.name ? option.name : "بدون نام"
}
getOptionValue={(option: AppDataType) => option.appID}
isRequired={true}
/>
)}
/>
</Grid>
<Grid item xs={12} md={4} lg={3}>
<Controller
name="roleId"
control={control}
render={({ field }) => (
<SelectField
selectRef={roleRef}
disabled={!watch("appId")}
isLoading={getRolesLoding}
{...field}
value={field.value}
onChange={async (val: GetRolesData) => {
if (!!val && val.roleID !== 0) {
field.onChange(val.roleID);
const data = await loadAssignMenuDataHandler(
{
params: {
_AppID: getValues("appId"),
_RoleID: val.roleID,
},
},
getUsersOptions,
"role"
);
dispatch({
type: AssignMenuActionTypes.SET_USERS,
payload: data as GetUsersData[],
});
}
}}
options={state.roleData}
label="نقش کاربر"
error={errors.appId?.message}
getOptionLabel={(option: GetRolesData) => option.roleName}
getOptionValue={(option: GetRolesData) => option.roleID}
isRequired={true}
/>
)}
/>
</Grid>
<Grid item xs={12} md={4} lg={3}>
<Controller
name="userId"
control={control}
render={({ field }) => (
<SelectField
disabled={!watch("roleId")}
selectRef={userRef}
isLoading={getUsersLoding}
{...field}
onChange={async (val: GetUsersData) => {
if (!!val && val.userID !== 0) {
field.onChange(val.userID);
const data = await loadAssignMenuDataHandler(
{
params: {
_AppID: getValues("appId"),
_RoleID: getValues("roleId"),
_UserID: val.userID,
},
},
getMenuOptions,
"user"
);
console.log(data, " menu data");
dispatch({
type: AssignMenuActionTypes.SET_MENU,
payload: data as GetMenuData[],
});
setOpen(true);
}
}}
options={state?.userData}
label="کاربر مورد نظر"
error={errors.appId?.message}
getOptionLabel={(option: GetUsersData) => option.name}
getOptionValue={(option: GetUsersData) => option.userID}
isRequired={true}
/>
)}
/>
</Grid>
</Grid>
{state.menuData && (
<>
<Button
color="primary"
disabled={getMenuLoding}
onClick={handleOpen}
>
لیست دسترسی ها
</Button>
{/* <ModalComponent
title="لیست منو ها"
openModal={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<div>
<ItemList
items={state.menuData && state.menuData}
checkedItems={checkedItems}
setCheckedItems={setCheckedItems}
/>
</div>
<div className="flex justify-end m-1 mt-3">
<Button
variant="contained"
onClick={() => setConfirmOpen(true)}
color="primary"
disabled={postUserAccessLoding}
>
ثبت دسترسی ها
</Button>
</div>
</ModalComponent> */}
</>
)}
<ConfirmModalComponent
confirmAction={handleSubmit(onSubmit)}
onClose={() => setConfirmOpen(false)}
openModal={confirmOpen}
title="آیا میخواهید تغییرات ثبت شود؟"
/>
</form>
</div>
);
};
export default AssignMneuForm;
import React, { useEffect, useState } from "react";
import { Checkbox, FormControlLabel } from "@mui/material";
import {
Accordion,
AccordionDetails,
AccordionSummary,
Typography,
} from "@src/imports";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { GetMenuData } from "@src/types/services/assignMenuType";
interface ItemListProps {
items: GetMenuData[];
checkedItems: number[];
setCheckedItems: React.Dispatch<React.SetStateAction<number[]>>;
}
const ItemList: React.FC<ItemListProps> = ({
items,
checkedItems,
setCheckedItems,
}) => {
const [openAccordions, setOpenAccordions] = useState<number[]>([]);
useEffect(() => {
console.log(checkedItems, " hereee");
}, [checkedItems]);
const handleCheckboxChange = (id: number) => {
if (!checkedItems.includes(id)) {
setCheckedItems((prev) => [...prev, id]);
} else {
setCheckedItems((prev) => prev.filter((item) => item !== id));
}
};
const handleAccordionToggle = (id: number) => {
if (!openAccordions.includes(id)) {
setOpenAccordions((prev) => [...prev, id]);
} else {
setOpenAccordions((prev) => prev.filter((item) => item !== id));
}
};
const getAllDescendantIds = (children: GetMenuData[]): number[] => {
const descendants: number[] = [];
const findDescendants = (items: GetMenuData[]) => {
items.forEach((item) => {
descendants.push(item.id);
if (item.child && item.child.length > 0) {
findDescendants(item.child);
}
});
};
findDescendants(children);
return descendants;
};
const getParentIds = (id: number): number[] => {
const parentIds: number[] = [];
let currentId = id;
const findParent = (items: GetMenuData[], parentId: number) => {
for (const item of items) {
if (item.id === currentId) {
parentIds.push(parentId);
return true;
}
if (item.child) {
const found = findParent(item.child, item.id);
if (found) {
parentIds.push(item.id);
return true;
}
}
}
return false;
};
findParent(items, 0);
return parentIds.reverse();
};
const handleParentCheckboxChange = (item: GetMenuData) => {
const allDescendants = getAllDescendantIds(item.child || []);
const isChecked = checkedItems.includes(item.id);
if (isChecked) {
setCheckedItems((prev) =>
prev.filter((id) => id !== item.id && !allDescendants.includes(id))
);
} else {
setCheckedItems((prev) => [
...new Set([...prev, item.id, ...allDescendants]),
]);
}
};
const handleChildCheckboxChange = (id: number, parentId: number) => {
console.log('button clicked')
const isChecked = checkedItems.includes(id);
handleCheckboxChange(id);
const parentIds = getParentIds(id);
if (!isChecked) {
setCheckedItems((prev) => [...new Set([...prev, ...parentIds, id])]);
} else {
const siblings = items.filter((item) => item.parentId === parentId);
const allSiblingsUnchecked = siblings.every(
(sibling) => !checkedItems.includes(sibling.id)
);
if (allSiblingsUnchecked) {
const validParentIds: number[] = [];
for (let i = parentIds.length - 1; i >= 0; i--) {
const pId = parentIds[i];
const foundItems = items.filter((item) => item.id === pId);
const children = foundItems[0]?.child;
if (children) {
const childIds = children.map((child) => child.id);
const childChecked = childIds.some(
(childId) => childId !== id && checkedItems.includes(childId)
);
if (!childChecked) {
validParentIds.push(pId);
}
}
}
setCheckedItems((prev) =>
prev.filter((itemId) => !validParentIds.includes(itemId))
);
}
}
};
const renderItems = (items: GetMenuData[]) => {
return items.map((item) => {
const hasChildren = item.hasChild;
const children = item.child || [];
const allChildrenChecked = children.every((child) =>
checkedItems.includes(child.id)
);
const someChildrenChecked = children.some((child) =>
checkedItems.includes(child.id)
);
return (
<div key={item.id}>
<div className="flex flex-row gap-1 items-center m-2">
{hasChildren && children.length > 0 && (
<Accordion
className="w-full"
expanded={openAccordions.includes(item.id)}
onChange={() => handleAccordionToggle(item.id)}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
className="!p-0"
>
<div className="flex flex-row gap-2 items-center justify-center align-middle">
<FormControlLabel
control={
<Checkbox
checked={allChildrenChecked}
indeterminate={
someChildrenChecked && !allChildrenChecked
}
onChange={() => handleParentCheckboxChange(item)}
/>
}
label={null}
/>
<Typography id="modal-modal-title">
{item.linkName}
</Typography>
</div>
</AccordionSummary>
<AccordionDetails className="flex flex-col gap-1">
{renderItems(children)}
</AccordionDetails>
</Accordion>
)}
{!hasChildren && (
<div className="flex flex-row gap-1 items-center justify-center align-middle">
<FormControlLabel
control={
<Checkbox
checked={checkedItems.includes(item.id)}
onChange={() =>
handleChildCheckboxChange(item.id, item.parentId)
}
/>
}
label={null}
/>
<Typography id="modal-modal-title">{item.linkName}</Typography>
</div>
)}
</div>
</div>
);
});
};
return (
<div className="max-h-[400px] overflow-auto flex flex-col gap-2">
{renderItems(items)}
</div>
);
};
export default ItemList;
The issue you're experiencing with the checkedItems not updating when using the ModalDrawer likely stems from the way the state is managed and possibly how React's state updates are batched.
Here's a comprehensive checklist and some tips to help you debug this issue:
1. Ensure State Updates Are Batched
Check if your modal component is being rendered multiple times, possibly due to state changes affecting the parent component. In React, state updates can be batched to improve performance. You could check if the setCheckedItems is being called multiple times in quick succession, which can lead to unexpected behaviors.
2. Update Logic in ItemList
When updating the checkedItems in the ItemList component, ensure that the logic functions correctly across multiple render cycles. You can try to simplify the update logic or ensure that updates to checkedItems do not conflict with the current value of checkedItems.
3. Ensure Context and State Flow
Verify that the context value supplied by ModalDrawerContext is being consumed properly. When you set checkedItems, it should ideally be using the setter provided by the context.
4. Use useEffect for Debugging
Add logging statements inside the ItemList where you set checkedItems to see if the set state function is being called with the right parameters. Also add logs inside handleCheckboxChange and handleChildCheckboxChange functions and see if they are invoked correctly:
const handleCheckboxChange = (id: number) => {
console.log("Checkbox clicked:", id); // Debug log
// Existing logic...
}
const handleChildCheckboxChange = (id: number, parentId: number) => {
console.log('Child checkbox clicked:', id); // Debug log
// Existing logic...
}
5. Check for Re-renders
If your ItemList component is re-rendered without the expected state, this might happen due to how props/state flow in your component hierarchy. Use React.memo for the ItemList component to prevent unnecessary re-renders.
6. Use Functional Updates
In the following code where you're setting the checked items, consider using the functional form of setState to avoid closure issues with stale state:
const handleCheckboxChange = (id: number) => {
setCheckedItems(prev => prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]);
}
7. Confirm Context Integration
Ensure that the ModalDrawer provider is set up correctly and isn't getting unmounted/re-mounted which could cause it to provide new values.
Wrap Up
Try addressing the points above step by step and see if it helps resolve the issue. If necessary, share some logging output or the results of the checks for further insights into what might be going wrong.
Here’s an adjusted function you might want to use for updating checkedItems that might help reduce complexity:
const handleCheckboxChange = (id: number) => {
setCheckedItems((prevCheckedItems) => {
if (prevCheckedItems.includes(id)) {
return prevCheckedItems.filter((item) => item !== id);
} else {
return [...prevCheckedItems, id];
}
});
};
This way, you're always working with the most recent state of checkedItems.
Moving the checkedItems state to a context can be a great solution, especially if you need to share the checked items across multiple components or if you find that prop drilling becomes cumbersome. Here’s how you can effectively implement a context for managing the checkedItems state, including steps and an example.
Steps to Implement a Context for checkedItems
-
Create a New Context: Create a context specifically for managing the checkedItems.
-
Provide State Management in the Provider: Set up a provider that holds the state for checkedItems and provides update functions.
-
Consume the Context: Replace the local state management in your ItemList and other components with the context.
-
Ensure Performance: Use React.memo for components that should not re-render unnecessarily.
Example Implementation
Here’s a step-by-step example based on your existing code structure:
1. Create the Context
Create a new file (e.g., CheckedItemsContext.tsx):
import React, { createContext, useContext, useState } from 'react';
const CheckedItemsContext = createContext(null);
export const CheckedItemsProvider = ({ children }) => {
const [checkedItems, setCheckedItems] = useState([]);
const toggleCheckedItem = (id) => {
setCheckedItems((prev) =>
prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]
);
};
return (
<CheckedItemsContext.Provider value={{
checkedItems,
toggleCheckedItem,
}}>
{children}
</CheckedItemsContext.Provider>
);
};
export const useCheckedItems = () => {
return useContext(CheckedItemsContext);
};
2. Wrap Your App with the Provider
You’ll need to wrap your application (or the relevant part of it) with the CheckedItemsProvider. For instance, in your main.tsx, wrap your application:
import { CheckedItemsProvider } from './context/CheckedItemsContext';
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Providers>
<BrowserRouter>
<ModalProvider>
<CheckedItemsProvider> {/* Add this line */}
<AuthProvider>
<ThemeProvider>
<App />
<ToastContainer
rtl
autoClose={10000}
position="top-left"
style={{ marginTop: "50px" }}
/>
</ThemeProvider>
</AuthProvider>
</CheckedItemsProvider> {/* Close here */}
</ModalProvider>
</BrowserRouter>
</Providers>
</React.StrictMode>
);
3. Consume the Context in Your Components
Modify your ItemList to use the new context:
import React from 'react';
import { Checkbox, FormControlLabel } from "@mui/material";
import { useCheckedItems } from '../context/CheckedItemsContext';
const ItemList = ({ items }) => {
const { checkedItems, toggleCheckedItem } = useCheckedItems();
return (
<div className="max-h-[400px] overflow-auto flex flex-col gap-2">
{items.map((item) => (
<div key={item.id}>
<FormControlLabel
control={
<Checkbox
checked={checkedItems.includes(item.id)}
onChange={() => toggleCheckedItem(item.id)}
/>
}
label={item.linkName}
/>
</div>
))}
</div>
);
};
export default ItemList;
4. Using ItemList in Your Modal
Ensure that wherever you use ItemList inside your modal, it will now interact with the global state provided by CheckedItemsContext.
const ModalContent = () => {
const items = [/* your item data */];
return (
<ItemList items={items} />
);
};
Advantages of Using Context
- Global State Management: You can access
checkedItems from any component that is a descendant of the CheckedItemsProvider, simplifying state management.
- Simplified Component Interfaces: You avoid passing props deeply through several layers by consuming context directly.
- Reactivity: The context will ensure that any consuming component is re-rendered when
checkedItems changes.
Considerations
- Performance: If many components consume the context but only need certain parts, consider using separate contexts for different state segments or optimize renders using
React.memo.
- Code Complexity: Introducing context adds another layer of complexity, so use it when your use case justifies this complexity.
By following these steps, you should be able to successfully manage the checkedItems in a context and resolve the issue with the checkboxes not updating correctly in the ModalDrawer.
Certainly! Let's modify the provided context and components to be TypeScript-safe while adhering to best practices for TypeScript in React.
Step 1: Create the Context in TypeScript
Create a new file named CheckedItemsContext.tsx (or use the appropriate name for your structure):
import React, { createContext, useContext, useState, ReactNode } from 'react';
// Define a context type
interface CheckedItemsContextType {
checkedItems: number[];
toggleCheckedItem: (id: number) => void;
}
// Create the context with a default value of 'null'
const CheckedItemsContext = createContext<CheckedItemsContextType | undefined>(undefined);
interface CheckedItemsProviderProps {
children: ReactNode;
}
export const CheckedItemsProvider: React.FC<CheckedItemsProviderProps> = ({ children }) => {
const [checkedItems, setCheckedItems] = useState<number[]>([]);
const toggleCheckedItem = (id: number) => {
setCheckedItems((prev) =>
prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]
);
};
return (
<CheckedItemsContext.Provider value={{
checkedItems,
toggleCheckedItem,
}}>
{children}
</CheckedItemsContext.Provider>
);
};
// Custom hook for easier access to context
export const useCheckedItems = (): CheckedItemsContextType => {
const context = useContext(CheckedItemsContext);
if (context === undefined) {
throw new Error("useCheckedItems must be used within a CheckedItemsProvider");
}
return context;
};
Step 2: Wrap Your App with the Provider
In your main.tsx, wrap your application with the CheckedItemsProvider:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { CheckedItemsProvider } from './context/CheckedItemsContext';
// Other imports...
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Providers>
<BrowserRouter>
<ModalProvider>
<CheckedItemsProvider>
<AuthProvider>
<ThemeProvider>
<App />
<ToastContainer
rtl
autoClose={10000}
position="top-left"
style={{ marginTop: "50px" }}
/>
</ThemeProvider>
</AuthProvider>
</CheckedItemsProvider>
</ModalProvider>
</BrowserRouter>
</Providers>
</React.StrictMode>
);
Step 3: Consume the Context in Your ItemList Component
Modify your ItemList to leverage the new context using TypeScript:
import React from 'react';
import { Checkbox, FormControlLabel } from "@mui/material";
import { useCheckedItems } from '../context/CheckedItemsContext';
interface Item {
id: number;
linkName: string;
}
interface ItemListProps {
items: Item[];
}
const ItemList: React.FC<ItemListProps> = ({ items }) => {
const { checkedItems, toggleCheckedItem } = useCheckedItems();
return (
<div className="max-h-[400px] overflow-auto flex flex-col gap-2">
{items.map((item) => (
<div key={item.id}>
<FormControlLabel
control={
<Checkbox
checked={checkedItems.includes(item.id)}
onChange={() => toggleCheckedItem(item.id)}
/>
}
label={item.linkName}
/>
</div>
))}
</div>
);
};
export default ItemList;
Step 4: Using ItemList in the Modal
Ensure wherever you use ItemList, you'll pass the correct props based on your application's needs. Here’s a simple example:
import React from 'react';
import ItemList from './ItemList';
import { GetMenuData } from '@src/types/services/assignMenuType';
interface ModalContentProps {
items: GetMenuData[];
}
const ModalContent: React.FC<ModalContentProps> = ({ items }) => {
const itemData = items.map(item => ({
id: item.id,
linkName: item.linkName,
}));
return <ItemList items={itemData} />;
};
Benefits of These Changes
- Type Safety: By defining interfaces for your context value and component props, you ensure that any changes to structure or types will be caught by TypeScript, reducing runtime errors.
- Custom Hook: The use of a custom hook for context access makes it easier and cleaner to consume context in multiple components and gives a clear error message if the context is not used within the provider.
- Cleaner Props Management: The use of interfaces for
Item and ItemListProps allows you to maintain a clear structure for your data and improves code readability.
By following these structured steps, you should be able to successfully implement and leverage a context for managing checkedItems while ensuring type safety in your TypeScript React application.