Igor
Igor4mo ago

Data Race in a useEffect

Hi, I have been using tRPC for a while, and it has been amazing. I am currently running into a small issue. In one of my components, I create a new project and onSuccess, I refresh the endpoints: const { mutate: createProjects } = trpc.createProjectsFromCsv.useMutation({ onSuccess: (data: { successfullProjects: any[], failedProjects: any[] }) => { setSuccessfullProjects(data.successfullProjects) setFailedProjects(data.failedProjects) utils.getUserProjects.invalidate() ** utils.getOrganizationProjects.invalidate()** utils.getVerifiedProjects.invalidate() setIsLoading(false) }, On another component, I read the existing projects and depending on them, I perform an action (search for duplicates) const { data: existingProjects, isLoading, refetch } = trpc.getOrganizationProjects.useQuery({id: activeOrganizationId}) useEffect(() => { if (!projects) return if (isLoading) return const allProjects = [...projects, ...existingProjects || []] let isDuplicate = false { code that figures out if there are duplicates and sets projectGroupings } if (!isDuplicate && refetchTries < 2) { refetch() setRefetchTries(refetchTries + 1) return } if (refetchTries >= 2) { setTab('review') } { more code that doesn't matter for this purpose } }, [activeOrganizationId, existingProjects, isLoading, projects, refetch, refetchTries, setTab])
1 Reply
Igor
Igor4mo ago
Problem: If this runs right after I created a project, it will trigger the if statement that sends the user to the review tab: if (refetchTries >= 2) { setTab('review') } However, if I refresh the page or try again, it will work. If I run it after I delete a project, the duplicate tab will appear for ~1 second, and then it will go to review, showing that there is a delay for the data to update. This has not happened before, and I am not sure how I can ensure the data is updated when this runs. Any ideas?