React Query Integration for Server State Sync in Clinet #245

Merged
admin merged 60 commits from react-query into main 2025-07-11 11:32:19 +00:00
5 changed files with 64 additions and 55 deletions
Showing only changes of commit 8676ff24a5 - Show all commits

View File

@ -152,7 +152,6 @@ export const useEmployeesAllOrByProjectId = (projectId, showInactive) => {
export const useEmployeeProfile = ( employeeId ) => export const useEmployeeProfile = ( employeeId ) =>
{ {
const isEnabled = !!employeeId; const isEnabled = !!employeeId;
const { const {
data = null, data = null,
isLoading: loading, isLoading: loading,
@ -190,11 +189,11 @@ export const useUpdateEmployee = () =>
const id = variables.id || variables.employeeId; const id = variables.id || variables.employeeId;
const isAllEmployee = variables.IsAllEmployee; const isAllEmployee = variables.IsAllEmployee;
// Cache invalidation // Cache invalidation
queryClient.invalidateQueries( [ 'allEmployee', isAllEmployee ] ); queryClient.invalidateQueries( {queryKey:[ 'allEmployee', isAllEmployee ] });
// queryClient.invalidateQueries(['employeeProfile', id]); // queryClient.invalidateQueries(['employeeProfile', id]);
// queryClient.invalidateQueries( {queryKey: [ 'projectEmployees' ]} ); queryClient.invalidateQueries( {queryKey: [ 'projectEmployees' ]} );
// queryClient.invalidateQueries( [ 'employeeListByProject' ,selectedProject] ); // queryClient.invalidateQueries( {queryKey:[ 'employeeListByProject']} );
showToast( `Employee ${ id ? 'updated' : 'created' } successfully`, 'success' ); showToast( `Employee ${ id ? 'updated' : 'created' } successfully`, 'success' );
}, },
onError: (error) => { onError: (error) => {
@ -220,7 +219,7 @@ export const useSuspendEmployee = ({ setIsDeleteModalOpen, setemployeeLodaing })
// queryClient.invalidateQueries( ['allEmployee',false]); // queryClient.invalidateQueries( ['allEmployee',false]);
queryClient.invalidateQueries( {queryKey: [ 'projectEmployees' ]} ); queryClient.invalidateQueries( {queryKey: [ 'projectEmployees' ]} );
queryClient.invalidateQueries( [ 'employeeListByProject' ,selectedProject] ); queryClient.invalidateQueries( {queryKey:[ 'employeeListByProject' ,selectedProject]} );
setIsDeleteModalOpen(false); setIsDeleteModalOpen(false);
}, },

View File

@ -1,7 +1,7 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { cacheData,getCachedData } from "../slices/apiDataManager"; import { cacheData,getCachedData } from "../slices/apiDataManager";
import { MasterRespository } from "../repositories/MastersRepository"; import { MasterRespository } from "../repositories/MastersRepository";
import { useQuery } from "@tanstack/react-query";
export const useMasterRole =()=>{ export const useMasterRole =()=>{
@ -43,40 +43,55 @@ export const useMasterRole =()=>{
return {masterRole,loading} return {masterRole,loading}
} }
export const useFeatures =()=> { // export const useFeatures =()=> {
const [masterFeatures, setMasterFeatures] = useState([]); // const [masterFeatures, setMasterFeatures] = useState([]);
const [loading, setLoading] = useState(true); // const [loading, setLoading] = useState(true);
const [error, setError] = useState(""); // const [error, setError] = useState("");
const fetchData = async () => { // const fetchData = async () => {
try { // try {
const features_cache = getCachedData("masterFeatures"); // const features_cache = getCachedData("masterFeatures");
if (!features_cache) { // if (!features_cache) {
MasterRespository.getFeatures() // MasterRespository.getFeatures()
.then((response) => { // .then((response) => {
setMasterFeatures(response.data); // setMasterFeatures(response.data);
cacheData("features", response.data); // cacheData("features", response.data);
setLoading(false) // setLoading(false)
}) // })
.catch((error) => { // .catch((error) => {
setError("Failed to fetch data."); // setError("Failed to fetch data.");
}); // });
}else{ // }else{
if (!masterFeatures.length) setMasterFeatures(features_cache); // if (!masterFeatures.length) setMasterFeatures(features_cache);
} // }
} catch (err) { // } catch (err) {
setError("Failed to fetch data."); // setError("Failed to fetch data.");
} finally { // } finally {
setLoading(false); // setLoading(false);
} // }
}; // };
useEffect(()=>{ // useEffect(()=>{
fetchData(); // fetchData();
},[]) // },[])
return{masterFeatures,loading} // return{masterFeatures,loading}
} // }
// -----------------Query- -------------------------
export const useFeatures = () => {
const {data=[],isLoading,error} = useQuery({
queryKey: ["masterFeatures"],
queryFn: async () => {
const response = await MasterRespository.getFeatures();
return response.data;
},
} );
return {
masterFeatures:data,loading:isLoading,error
}
};

View File

@ -360,7 +360,8 @@ export const useCreateProject = ({ onSuccessCallback }) => {
}, },
onSuccess: (data) => { onSuccess: (data) => {
// Invalidate the cache // Invalidate the cache
queryClient.invalidateQueries(['ProjectsList']); queryClient.invalidateQueries( {queryKey: [ 'ProjectsList' ]} );
queryClient.invalidateQueries({queryKey:['basicProjectNameList']});
// Emit event for consumers (like useProjects or others) // Emit event for consumers (like useProjects or others)
eventBus.emit("project", { eventBus.emit("project", {
@ -397,8 +398,9 @@ export const useUpdateProject = ({ onSuccessCallback }) => {
{ {
const { projectId } = variables; const { projectId } = variables;
queryClient.invalidateQueries(["ProjectsList"]); queryClient.invalidateQueries({queryKey:["ProjectsList"]});
queryClient.invalidateQueries(["projectinfo", projectId]); queryClient.invalidateQueries( {queryKey: [ "projectinfo", projectId ]} );
queryClient.invalidateQueries({queryKey:['basicProjectNameList']});
eventBus.emit("project", { eventBus.emit("project", {
keyword: "Update_Project", keyword: "Update_Project",
@ -437,7 +439,7 @@ export const useManageProjectInfra = ( {onSuccessCallback} ) =>
onSuccess: ( data, variables ) => onSuccess: ( data, variables ) =>
{ {
const { projectId } = variables; const { projectId } = variables;
queryClient.invalidateQueries(["ProjectInfra", projectId]); queryClient.invalidateQueries({queryKey:["ProjectInfra", projectId]});
if (onSuccessCallback) onSuccessCallback(data,variables); if (onSuccessCallback) onSuccessCallback(data,variables);
}, },
onError: (error) => { onError: (error) => {
@ -465,7 +467,7 @@ export const useManageProjectAllocation = ({
return response.data; return response.data;
}, },
onSuccess: (data, variables, context) => { onSuccess: (data, variables, context) => {
queryClient.invalidateQueries(['empListByProjectAllocated']); queryClient.invalidateQueries({queryKey:['empListByProjectAllocated']});
if (variables?.added) { if (variables?.added) {
showToast('Employee Assigned Successfully', 'success'); showToast('Employee Assigned Successfully', 'success');
@ -499,7 +501,7 @@ export const useManageTask = ({onSuccessCallback}) =>
mutationFn: async ( payload ) => await ProjectRepository.manageProjectTasks( payload ), mutationFn: async ( payload ) => await ProjectRepository.manageProjectTasks( payload ),
onSuccess: ( data, variables ) => onSuccess: ( data, variables ) =>
{ {
queryClient.invalidateQueries(["WorkItems"]) queryClient.invalidateQueries({ queryKey: ["WorkItems"] })
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => onError: (error) =>
@ -523,7 +525,7 @@ export const useDeleteProjectTask = (onSuccessCallback) => {
onSuccess: ( _, variables ) => onSuccess: ( _, variables ) =>
{ {
showToast("Task deleted successfully", "success"); showToast("Task deleted successfully", "success");
queryClient.invalidateQueries([ "WorkItems",variables.workAreaId]); queryClient.invalidateQueries({queryKey:[ "WorkItems",variables.workAreaId]});
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
}, },
onError: (error) => { onError: (error) => {

View File

@ -178,7 +178,7 @@ export const useCreateTask = ( {onSuccessCallback, onErrorCallback} = {} ) =>
}, },
onSuccess: ( _, variables ) => onSuccess: ( _, variables ) =>
{ {
queryClient.invalidateQueries(["taskList"]); queryClient.invalidateQueries({queryKey:["taskList"]});
showToast( "Task Assigned Successfully.", "success" ); showToast( "Task Assigned Successfully.", "success" );
if (onSuccessCallback) onSuccessCallback(variables); if (onSuccessCallback) onSuccessCallback(variables);
}, },

View File

@ -39,7 +39,7 @@ const EmployeeList = () => {
const { employees, loading, setLoading, error, recallEmployeeData } = const { employees, loading, setLoading, error, recallEmployeeData } =
useEmployeesAllOrByProjectId( useEmployeesAllOrByProjectId(
showAllEmployees ? null : selectedProjectId, // Use selectedProjectId here showAllEmployees ? null : selectedProjectId,
showInactive showInactive
); );
@ -68,25 +68,18 @@ const EmployeeList = () => {
const navigate = useNavigate(); const navigate = useNavigate();
/**
* Applies the search filter to a given array of employee data.
* @param {Array} data - The array of employee objects to filter.
* @param {string} text - The search text.
* @returns {Array} The filtered array.
*/
const applySearchFilter = (data, text) => { const applySearchFilter = (data, text) => {
if (!text) { if (!text) {
return data; return data;
} }
const lowercasedText = text.toLowerCase().trim(); // Ensure search text is trimmed and lowercase const lowercasedText = text.toLowerCase().trim();
return data.filter((item) => { return data.filter((item) => {
// **IMPROVED FULL NAME CONSTRUCTION**
const firstName = item.firstName || ""; const firstName = item.firstName || "";
const middleName = item.middleName || ""; const middleName = item.middleName || "";
const lastName = item.lastName || ""; const lastName = item.lastName || "";
// Join parts, then trim any excess spaces if a middle name is missing
const fullName = `${firstName} ${middleName} ${lastName}`.toLowerCase().trim().replace(/\s+/g, ' '); const fullName = `${firstName} ${middleName} ${lastName}`.toLowerCase().trim().replace(/\s+/g, ' ');
const email = item.email ? item.email.toLowerCase() : ""; const email = item.email ? item.email.toLowerCase() : "";