I have a react query problem. the very first edit I submit does not invalidate the data. but if I defocus and refocus the browser window it starts invalidating correctly after each mutation without the need to defocus. why is that?
` const queryClient = useQueryClient()
const fetchCaseData = async () => {
const caseService = await GetCaseService()
return caseService.getCaseWithAssets(projectId, caseId)
}
useQuery(
[projectId, caseId],
fetchCaseData,
{
enabled: !!projectId && !!caseId,
onSuccess: (result) => {
console.log("Case data fetched successfully:", result)
},
onError: (error: Error) => {
console.error("Error fetching data:", error)
setSnackBarMessage("Case data not found. Redirecting back to project")
navigate("/")
},
},
)
const { data: apiData } = useQuery<Components.Schemas.CaseWithAssetsDto | undefined>(
[projectId, caseId],
() => queryClient.getQueryData([projectId, caseId]),
{
enabled: !!projectId && !!caseId,
initialData: () => queryClient.getQueryData([projectId, caseId]),
},
)
const mutation = useMutation(
async ({ serviceMethod }: {
projectId: string,
caseId: string,
resourceId?: string,
resourceProfileId?: string,
wellId?: string,
drillingScheduleId?: string,
serviceMethod: object,
}) => serviceMethod,
{
onSuccess: (
results: any,
variables,
) => {
const { projectId, caseId } = variables
queryClient.invalidateQueries([projectId, caseId])
},
onError: (error: any) => {
console.error("Failed to update data:", error)
},
},
)
const updateCase = async (
projectId: string,
caseId: string,
resourcePropertyKey: ResourcePropertyKey,
value: any,
resourceObject?: ResourceObject,
) => {
const caseService = await GetCaseService()
const existingDataInClient: Components.Schemas.CaseWithAssetsDto | undefined = queryClient.getQueryData([projectId, caseId])
const caseObjectFromClient = existingDataInClient?.case
const updatedData = resourceObject || { ...caseObjectFromClient, [resourcePropertyKey]: value }
const serviceMethod = caseService.updateCase(projectId, caseId, updatedData as Components.Schemas.CaseDto)
try {
return await mutation.mutateAsync({
projectId,
caseId,
serviceMethod,
})
} catch (error) {
return false
}
}`
I am trying to submit data edits. when I do, I need to refetch from the api, because some of the values are generated in the back end and needs to replace the old one. this re-fetching process does not happen on first mutation attempt, but it does work as expected if I de-focus the window once after the failed attempt. then it works as expected every time going forward
Arian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.