Many mobile apps need to load resources from remote URLs. You might want to make a POST request to a REST API, or you might need to fetch a large amount of static content from another server.
This feature depends on the http service provided by the integrated Lynx Service.
Lynx provides the Fetch API with the same usage as the Web. You can refer to the MDN guides on Using Fetch for more information.
This is an example app that fetches and displays user posts provided by the JSONPlaceholder API. It initializes with a loading state and, upon mounting, triggers a Fetch API request to retrieve posts. The fetched data is then displayed in a scrollable list where each post is shown with its ID and title. If the request is still in progress, a "Loading..." message appears.
In order to fetch content from an arbitrary URL
, you can pass the URL
to fetch
:
fetch
also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers
, make a POST
request, or provide JSON-based body
:
Take a look at the Fetch Request for the properties supported by Lynx.
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. fetch
method will return a Promise
that makes it straightforward to write code that works in an asynchronous manner. You can use the async/await
syntax to wait the promise
to end:
Take a look at the Fetch Response for the properties supported by Lynx.
Don't forget to catch any errors that may be thrown by fetch
, otherwise they will be dropped silently.
Since The Fetch API is built into Lynx. This means that you can use third party libraries that depend on it.
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 Web 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 Web ecosystem.
For frontend framework-specific data fetching solutions, such as using TanStack Query (React Query) in ReactLynx, you can refer to the Data Fetching chapter of ReactLynx guide.