tezvyn:

React Native: Making Network Requests with Fetch

AI-drafted, machine-checkedSource: reactnative.devbeginner

fetch is your app's tool for requesting server data. It's asynchronous, returning a promise for a future response. Use it for API calls like loading profiles or posting updates. The footgun: always `catch` errors, or they will fail silently.

WHY IT EXISTS Mobile apps rarely exist in a vacuum. They need to communicate with servers to get fresh data, update user information, or download resources. React Native needed a standard, built-in way to handle these network requests that felt familiar to web developers.

THE MENTAL MODEL Think of fetch as placing an order at a restaurant. You give your order (the request URL and options) to the waiter, who gives you a ticket (a Promise). You don't get your food immediately; you wait for the kitchen to prepare it. When it's ready, the waiter brings you your dish (the response). You then have to process that dish, like parsing the JSON, before you can use it.

HOW IT WORKS The fetch function takes a URL as its first argument. For a simple GET request, that's all you need. For more complex requests like POST, you provide a second argument: an options object where you can specify the method ('POST'), headers (like 'Content-Type': 'application/json'), and a body (often a stringified JSON object). Since networking is asynchronous, fetch returns a Promise. You can handle this with .then() chains or, more commonly, with async/await inside an async function. The first await gets the raw response object; a second await on response.json() is needed to parse the JSON body.

WHEN TO USE IT Use fetch for most standard network communication in a React Native app. It's ideal for interacting with REST APIs, downloading static content like configuration files, or sending data back to a server. Because it's built-in, you don't need to add any third-party libraries for basic networking.

WHEN NOT TO USE IT For real-time, bi-directional communication, WebSockets are a better fit. If your app requires complex request logic, interceptors, or automatic retries, a library like Axios (which uses XMLHttpRequest under the hood) can provide that functionality out of the box, saving you from writing boilerplate code. Also, be aware of known issues with cookie-based authentication and manual redirects.

ONE CANONICAL EXAMPLE Here is how to fetch a list of movies from an API using async/await. Notice the try...catch block to handle potential network errors, which would otherwise fail silently.

const getMovies = async () => { try { const response = await fetch('https://reactnative.dev/movies.json'); const json = await response.json(); return json.movies; } catch (error) { console.error('Failed to fetch movies:', error); } };

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.