Since Reactlit scripts are async functions, you can fetch data directly in your script. This works fine for simple use cases,
but you should keep in mind that every time the script runs your fetch will be called.
Generally, we recommend using a cache to store your data. To accomplish this, you can use solutions like Next.js request memoization
or Tanstack Query.
This will display a loading state while the data is being fetched, but then clear it.
Let’s take a look at the example from the basics guide, and see how it would work with async fetching and some request latency.
While this app works okay, the loader appears even as you type text into the
inputs (see caching discussion above). In fact, any update triggers loading
the data again. Furthermore, the app does not disable interaction, if you try
to type while the data is loading, your entry might revert, resulting in a
poor user experience. This effect is more significant if the fetching is
slower. If your API is very fast you may not need to worry about these issues.
Next, we’ll explore using the data fetching plugin to solve these issues.
Data Fetching Plugin
The above fetching method works fine for simple use cases, but when you add a cache,
you will need to coordinate invalidating the cache and triggering a re-render when the data changes.
Additionally, the other components in your app have no way of responding to the loading state
of the data and your app essentially pauses to wait for the data to load.
The Data Fetching Plugin offers solutions to these problems. It is built on top of Tanstack Query and provides a type-safe way to create a
DataFetcher instance which can be used to get the current data synchronously, detect loading state, and update and invalidate the cache.
The following is an example of how you could use this plugin to improve the data fetching from above.
The following app behaves much more smoothly even with a slower API.