← Back to Chapters

React Native POST API

? React Native POST API

? Quick Overview

In React Native, a POST API request is used to send data to a server. This is commonly done for login forms, registrations, submitting data, or saving records in a database.

? Key Concepts

  • POST requests send data in the request body
  • fetch() is the most common method
  • Headers define content type
  • Data is usually sent as JSON
  • Responses are handled asynchronously

? Syntax / Theory

A POST request uses the HTTP method POST and includes a body containing data. In React Native, this is done using the fetch() API with proper headers and JSON formatting.

? Code Example

? View Code Example
// Import required hooks
import React, { useState } from "react";
import { View, Button, Text } from "react-native";

// Function to send POST request
const postData = async () => {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        title: "Hello World",
        body: "This is a new post",
        userId: 1
      })
    });
    
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.error(error);
  }
};

// Main component
export default function App() {
  return (
    <View>
      <Button title="Send Data" onPress={postData} />
    </View>
  );
}

? Interactive Simulator

Test the POST logic below. This simulates a mobile app sending data to a placeholder API.

App Simulator
// Console Output will appear here...

? Live Output / Explanation

What Happens?

  • Button press triggers the POST request
  • Data is sent to the server (jsonplaceholder)
  • Server responds with created object (ID 101)
  • Response is logged in console

? Interactive Flow

? User taps button → ? App sends POST request → ?️ Server processes data → ✅ Response returned

? Use Cases

  • User login and authentication
  • Registration forms
  • Submitting feedback
  • Saving data to database
  • Uploading form data

✅ Tips & Best Practices

  • Always set correct headers
  • Use async/await for cleaner code
  • Handle errors with try/catch
  • Validate data before sending
  • Use environment variables for API URLs

? Try It Yourself

  • Change API URL to your backend
  • Add input fields and send dynamic data
  • Handle error responses
  • Show success message on UI
  • Store response using state