🇺🇸
Continuing my previous post about React Query, today I bring the two main hooks: useQuery and useMutation:
useQuery:
- Used for data fetching.
- Main configurations:
-
queryKey
: The information key, which uniquely identifies the data you are fetching. -
queryFn
: The asynchronous function that makes the API request, returns the data, and populates the cache.
-
- How it works:
- When we need to return data,
useQuery
checks for the existence of the data in theQueryCache
using thequeryKey
. - If the data exists:
useQuery
returns the data directly from the cache, avoiding unnecessary API requests. - If the data does not exist: The
queryFn
is activated, making the API request, returning, and saving the data to theQueryCache
.
- When we need to return data,
useMutation:
- Used for operations that modify data (POST, PUT, PATCH, DELETE).
- Main configurations:
-
mutationFn
: Asynchronous function that sends the request to the API, performing the creation, update, or deletion operation on the server. -
onSuccess
: Callback function that allows you to perform specific actions when the mutation is successful, such as updating the cache or displaying a confirmation message. -
onError
: Callback function that allows you to handle errors in a personalized way, displaying error messages or performing other recovery actions. -
invalidateQueries
: Function that makes the data obsolete within the cache, because we changed the data on the server.
-
- How it works:
- The
mutationFn
function is executed, sending the request to the API. - After the request is completed, the
onSuccess
andonError
callbacks are called, depending on the result of the operation. - If the mutation changes data that is already in the cache,
invalidateQueries
should be used withinonSuccess
to make the data obsolete and ensure that the cache is updated throughuseQuery
- The
🇧🇷
Continuando meu post anterior sobre React Query, hoje trago os dois principais hooks: useQuery e useMutation:
useQuery:
- Utilizado para buscas de dados
-
Configurações principais:
-
queryKey
: A chave da informação, que identifica de forma única os dados que você está buscando. -
queryFn
: A função assíncrona que realiza a requisição à API e retorna os dados e alimenta o cache.
-
-
Funcionamento:
- Quando precisamos retornar um dado, o
useQuery
verifica a existência do dado noQueryCache
por meio daqueryKey
. - Caso o dado exista:
- O
useQuery
retorna os dados diretamente do cache, evitando requisições desnecessárias à API.
- O
- Caso o dado não exista:
- A
queryFn
é ativada, fazendo a requisição à API, retornando e salvando o dado noQueryCache
.
- A
- Quando precisamos retornar um dado, o
useMutation:
- Utilizado em operações que modificam os dados (POST, PUT, PATCH, DELETE).
-
Configurações Principais:
-
mutationFn
: Função assíncrona que envia a requisição para a API, realizando a operação de criação, atualização ou exclusão no servidor. -
onSuccess
: Função de callback que permite executar ações específicas quando a mutação é bem-sucedida, como atualizar o cache ou exibir uma mensagem de confirmação. -
onError
: Função de callback que permite tratar erros de forma personalizada, exibindo mensagens de erro ou executando outras ações de recuperação. -
invalidateQueries
: Função que torna os dados obsoletos dentro do cache, pois alteramos os dados no servidor
-
-
Funcionamento:
- A função
mutationFn
é executada, enviando a requisição para a API. - Após a conclusão da requisição, os callbacks
onSuccess
,onError
são chamados, dependendo do resultado da operação. - Caso a mutação altere dados que já estão no cache, o
invalidateQueries
deve ser usado dentro doonSuccess
para tornar o dado obsoleto garantir que o cache seja atualizado por meio do useQuery.
- A função