0
  const queryKey = ref("userData");

  const { data, isLoading, error } = useQuery({
    queryKey: [queryKey], // Chave única para identificar a consulta
    queryFn: async () => {
      const response = await makeReq.get(`users/data`, {
        withCredentials: true,
      });
      return response.data; // Retornando os dados da resposta
    },
  });

  const logout = async () => {
    try {
      const result = await Swal.fire({
        title: "Tem certeza que deseja sair?",
        text: "Você terá que refazer o login",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim",
      });

      if (result.isConfirmed) {
        await makeReq.post("users/logout", {}, { withCredentials: true });
        queryKey.value = "";

        setTimeout(() => {
          router.push("/");
        }, 1000);
      }
    } catch (err) {
      Swal.fire({
        title: "Ops... Erro interno",
        text: "Volte mais tarde",
        icon: "error",
        showCancelButton: false,
        confirmButtonText: "Voltar",
      });
      console.log(err);
    }
  };

The code above would be a piece of what would be my header, I use this component in some places in my application, my intention is whenever the user logs out through my logout function it throws it to the main route "/" the problem is that when I do this the old state remains and the header does not show the data that I would like it to show.

I tried to use the query invalidation but apparently I don't understand very well how it works and even though I really believe it's right, it doesn't work...

An important detail, the code above works, however, there is obviously something wrong with it, it doesn't seem right to me to use setTimeout in this way

1 Answer 1

1

try:

queryClient.invalidateQueries({ queryKey: ["userData"] }) to refetch fresh data.

and queryClient.removeQueries({ queryKey: ["userData"] }) to completely clear cached user data.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm, okay, that apparently worked, I don't understand why but thanks
Like I said; you do that to refetch fresh data and to completely clear cached user data; otherwise you'll refertch cahed ones, which means you get the old state. If you found my answer to be helful; It will be helpful to mark it as accepted answer. Have a good day!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.