I have a list of roleIds that is updated when ever a user selects a role from my select field The select field accepts selecting multiple options and removing a selected option hence adding and removing roleIds to my list dynamically.
I need help on how I can fetch data from the same endpoint for all the Ids in my roleIds list and how I can be able to use this data with out running into issue such as having my component rendering into endless loops and the Maximum update depth exceeded warnings
This is what I tried I have provided the fetcher I used and the useMultipleRolePrivileges function I used which returns a promise and I am thinking it is one of the reasons I am failing to manage my state
export const fetcher = (urls:string[])=>
urls.map((url)=> AuthenticatedAPIInstance.get(url).then((res) => res.data))
export const useMultipleRolePrivileges = (roleIds: any[]) => {
console.log("request made for these roles", roleIds)
const url = roleIds.map((roleid) => `/role_privileges?role_id=${roleid}`);
const { data, error } = useSWR(url, fetcher);
const privilegeData: any = [];
data?.map((item, index) =>
item.then((value) => privilegeData.push({ value: value, id: roleIds[index] }))
);
const loading = !data && !error;
return {
loading,
privilegeData,
};
};
This is where I use the useMultipleRolePrivileges in my component and it is acting not as expected
Part of my component logic
const { loading: rolePrivilegesLoading, privilegeData:rolePrivileges } = useMultipleRolePrivileges(
trialIds
)
const changeHandler = (e:any)=>{
const selectedIds: any[] = []
for (const option of e.selectedOptions){
selectedIds.push(option.value)
}
setTrialIds(selectedIds)
}
What I need is to be able to fetch the privilegeData when ever my roleId is updated in my changeHandler and remove the corresponding privilegeData for an Id removed as seen above or a more efficient way to do that