How do I call the same query from the same component?

Viewed 31

I have a query setup like so:

   ...
   doesProjectExist: build.query({
     query: (projectNumber) => ({
     url: `${URL}/exists/${projectNumber}`,
     method: "GET",
   }),
...

export const {
  useDoesProjectExistQuery
} = projectsSlice;

As the user selects a project, this query is called to see if it exists.

  const {
    data: existingProject,
    isLoading: isLoadingExistingProject,
    isSuccess: isSuccessExistingProject,
  } = useDoesProjectExistQuery(
    projectToCheckIfExists ? projectToCheckIfExists.projectNumber : skipToken
  );

  useEffect(() => {
    console.log("Existing Project", existingProject);
    console.log("Loading Existing Project", isLoadingExistingProject);
    console.log("Success Existing Project", isSuccessExistingProject);
  }, [existingProject, isLoadingExistingProject, isSuccessExistingProject]);

The use effect spits out results 3 times, 2 of them show isSuccess = true but one has existing project as true and one with false, making it impossible to evaluate. chrome console results

If I change the query to a mutation and deconstruct the hook like so:

  const [doesProjectExist, { isLoading }] =
    useDoesProjectExistMutation(skipToken);

I can call doesProjectExist at will and unwrap the results. Is there a way to call and unwrap a query directly? Using mutation seems wrong. I feel like I am missing something easy!

1 Answers

I guess that it's expected behavior. The case when you have both isLoadingExistingProject and isSuccessExistingProject set to false - is most likely a case when you pass the skipToken, due to projectToCheckIfExists may be undefined during lifecycle changes.

To investigate it in a more clear way, try to do something like more straightforward:

const {
    data: existingProject,
    isLoading: isLoadingExistingProject,
    isSuccess: isSuccessExistingProject,
  } = useDoesProjectExistQuery(
     projectToCheckIfExists?.projectNumber, 
     { skip: !projectToCheckIfExists}
  );

useDoesProjectExistQuery may not expect undefined in params, but it's up to you to make it handle undefined, or add some null check to param like projectToCheckIfExists?.projectNumber ?? 0, which will never be passed due to skip condition.

Not as clear as your notation with skipToken, but it should be more predictable.

Related