DEV Community

Preston "Brady" Adger
Preston "Brady" Adger

Posted on

Making async requests simple

If you're a front-end web developer, you will inevitably run into the predicament of managing your asynchronous call workflow. You want to write clean code AND provide a seamless experience for the end-user.

A single data fetch requires several variables to capture the various states of your request...

1). The data being returned from the query.
2). The state of the data fetch.
3). Error handling.
4). Pagination?
5). Refetching of data if dependent variables change.

The list goes on and on depending on the demands of the application. Add more than a single data fetch and your code can quickly spiral out of control with multiple variables and similar naming conventions.

Enter Tanstack Query. TanStack Query is an asynchronous state management tool for various web frameworks, including popular ones such as Vue and React. Using the example of asynchronous querying, this lightweight library allows for a simple function call, passing your asynchronous request, and returning a SINGLE object.

const fetchBlog = useQuery({
queryFn: () => <async_call_to_fetch_blog>
})

The fetchBlog object now contains the essential goodies for rendering your component/page, such as fetchBlog.data, fetchBlog.isLoading, fetchBlog.refetch(), fetchBlog.error, and many other useless tools. You can also destructure the assignment to look like { data, isLoading, refetch, error }. Pair this with a state management tool of your choosing and your speed, efficiency, and clarity will soar!

Top comments (0)