Whether fetching static content from a remote server or interacting with a REST API, ReactLynx applications often need to retrieve data from external sources. For example, you might want to load user posts in a social media app or fetch the latest product listings in an e-commerce application.
Lynx provides the Fetch API, enabling you to make network requests. You can refer to the Networking chapter for more details. The Fetch API provided by Lynx can be used together with server state management libraries from the React ecosystem, such as TanStack Query (React Query), to simplify data fetching and state management.
It is important to note that Lynx's Fetch API has subtle differences compared to the Web Fetch API. You can check the Fetch API Reference - Compatibility section to learn more about these differences. As a result, you may need to adapt libraries from the React ecosystem to ensure compatibility. If you encounter any issues on Lynx Fetch API, you are welcome to submit feature requests or contribute to help Lynx better support the React ecosystem.
TanStack Query is a popular server state management library in the React ecosystem, helping developers easily manage data fetching and caching.
The following example application shows how to use TanStack Query with the Fetch API in ReactLynx to fetch, display, and delete user posts provided by the JSONPlaceholder API.
The application first uses the useQuery
hook from TanStack Query to call fetchPosts
, fetching and displaying the first 10 posts. When the user clicks the "Delete Post 1" button, it triggers an Optimistic Update using the useMutation
hook: the post with id
1 is immediately removed from the list, and the deletePost
function calls the Fetch API to send a delete request. If the request fails, the state will roll back to its original state.