Hello fellow developers in this article we are going to discuss about Queries one of the three core concept or react-query.
A query is declarative dependency on an asynchronous source of data that is tied to unique key. A query can be used with any Promises based method to fetch data from s server.
To subscribe a query in your component or custom hooks, call useQuery
hook with at least:
- A unique key for query
- A function that returns promise that:
- Resolves data, or
- Throw an error
import { useQuery } from '@tanstack/react-query' function App() { const info = useQuery(['todos'], fetchTodoList) }
The unique key you provide will be used internally for refetching, caching, and sharing your query throughout your application.
The query results returned by useQuery
contains all of information about query that you’ll need for templating and any other usage of data:
const result = useQuery(['todos'], fetchTodoList)
Now the result contains following features we need to discuss.
isLoading
: Query has no data yetisError:
Query has encountered an errorisSuccess
– Query is successful and data is available
let’s see an example:
function Todos() { const { isLoading, isError, data, error } = useQuery(['todos'], fetchTodoList) if (isLoading) { return <span>Loading...</span> } if (isError) { return <span>Error: {error.message}</span> } // We can assume by this point that `isSuccess === true` return ( <ul> {data.map(todo => ( <li key={todo.id}>{todo.title}</li> ))} </ul> ) }
That’s it for this blog feel free to comment if there are any doubts.