Networking and Storage

Back

Loading concept...

🌐 React Native Networking & Storage

Your Phone’s Secret Messengers and Memory Box


🎭 The Story: Your App’s Postal Service

Imagine your phone is a tiny house. Inside lives a helpful elf (your app). This elf needs to:

  • Send letters to faraway places (servers) and get replies
  • Remember things even when the house loses power
  • Know when the road is blocked (no internet)

This is what Networking and Storage is all about! Let’s meet our helpers.


📬 Fetch API: The Mailman

What is it? The Fetch API is like a mailman who delivers letters (requests) and brings back replies (responses).

Simple Example: Asking for a Joke

// Send a letter asking for a joke
const getJoke = async () => {
  const response = await fetch(
    'https://api.jokes.com/random'
  );
  const joke = await response.json();
  console.log(joke.text);
};

How It Works

graph TD A["📱 Your App"] -->|Send Request| B["📬 Mailman"] B -->|Delivers| C["🌐 Server"] C -->|Reply| B B -->|Brings Back| A

Sending Different Types of Letters

Method What It Does Example
GET Ask for info “Give me today’s weather”
POST Send new info “Here’s my new photo”
PUT Update info “Change my name to Max”
DELETE Remove info “Delete my old post”

🚨 Error Handling Network: When Things Go Wrong

Sometimes the mailman gets lost, or the road is closed. We need to handle these problems!

The Three Bad Things That Can Happen

  1. Network Error - No road to travel (no internet)
  2. Server Error - The destination is broken (500 errors)
  3. Bad Request - You wrote the wrong address (404 errors)

Safe Fetching Example

const safeFetch = async (url) => {
  try {
    const response = await fetch(url);

    // Check if server said "OK"
    if (!response.ok) {
      throw new Error(
        `Server said: ${response.status}`
      );
    }

    return await response.json();
  } catch (error) {
    // Something went wrong!
    console.log('Oops:', error.message);
    return null;
  }
};

Common Error Codes

Code Meaning Like Saying…
200 Success “Got it!”
400 Bad Request “I don’t understand”
401 Unauthorized “Who are you?”
404 Not Found “That doesn’t exist”
500 Server Error “I’m broken!”

✋ Request Cancellation: Saying “Never Mind!”

What if you send a letter but change your mind? You can tell the mailman to stop and come back!

Why Cancel?

  • User navigates away from the screen
  • User types a new search (cancel old one)
  • Taking too long

AbortController: The Stop Sign

// Create a stop sign
const controller = new AbortController();

// Give it to the mailman
fetch('https://api.example.com/data', {
  signal: controller.signal
});

// Yell "STOP!" when needed
controller.abort();

Real Example: Search Box

let controller = null;

const search = async (text) => {
  // Cancel previous search
  if (controller) {
    controller.abort();
  }

  // New stop sign for this search
  controller = new AbortController();

  try {
    const result = await fetch(
      `/search?q=${text}`,
      { signal: controller.signal }
    );
    return await result.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Search cancelled');
    }
  }
};

🔐 Auth Token Handling: Your VIP Pass

Some doors only open for special people. An Auth Token is like a VIP pass that proves who you are.

The Token Flow

graph TD A["🔑 Login"] -->|Get Token| B["📦 Store Token"] B -->|Every Request| C["🎫 Attach Token"] C -->|Server Checks| D["✅ Access Granted"]

Storing and Using Tokens

// Save token after login
const saveToken = async (token) => {
  await AsyncStorage.setItem(
    'authToken',
    token
  );
};

// Use token in every request
const fetchWithAuth = async (url) => {
  const token = await AsyncStorage.getItem(
    'authToken'
  );

  return fetch(url, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
};

Token Refresh

Tokens expire like milk! When they go bad:

const smartFetch = async (url) => {
  let response = await fetchWithAuth(url);

  // Token expired?
  if (response.status === 401) {
    // Get fresh token
    await refreshToken();
    // Try again
    response = await fetchWithAuth(url);
  }

  return response;
};

📁 File Upload and Download: Sending Packages

Letters are small. But what about sending big packages like photos and documents?

Uploading a Photo

const uploadPhoto = async (photoUri) => {
  // Pack the photo in a box (FormData)
  const formData = new FormData();
  formData.append('photo', {
    uri: photoUri,
    type: 'image/jpeg',
    name: 'my-photo.jpg'
  });

  // Send the package
  const response = await fetch(
    'https://api.example.com/upload',
    {
      method: 'POST',
      body: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );

  return response.json();
};

Downloading a File

import RNFS from 'react-native-fs';

const downloadFile = async (url, filename) => {
  const path = `${RNFS.DocumentDirectoryPath}/${filename}`;

  const download = RNFS.downloadFile({
    fromUrl: url,
    toFile: path,
    progress: (res) => {
      const percent = (res.bytesWritten / res.contentLength) * 100;
      console.log(`Downloaded: ${percent}%`);
    }
  });

  await download.promise;
  return path;
};

📦 AsyncStorage: The Memory Box

AsyncStorage is like a memory box where your app stores things it wants to remember later—even after closing the app!

Basic Operations

import AsyncStorage from
  '@react-native-async-storage/async-storage';

// Save something
await AsyncStorage.setItem('name', 'Alex');

// Get it back
const name = await AsyncStorage.getItem('name');
console.log(name); // "Alex"

// Remove it
await AsyncStorage.removeItem('name');

// Clear everything
await AsyncStorage.clear();

Storing Objects

AsyncStorage only stores strings. For objects, we convert them:

// Save an object
const user = { name: 'Alex', age: 10 };
await AsyncStorage.setItem(
  'user',
  JSON.stringify(user)
);

// Get it back
const data = await AsyncStorage.getItem('user');
const savedUser = JSON.parse(data);

When to Use AsyncStorage

✅ Good For ❌ Not Good For
User settings Large files
Auth tokens Sensitive passwords
Small cache Real-time data
Preferences Images/videos

📡 NetInfo API: The Road Checker

NetInfo is like a road inspector who tells you:

  • Is the road open? (connected)
  • What type of road? (wifi/cellular)

Check Connection Status

import NetInfo from
  '@react-native-community/netinfo';

// Check right now
const checkConnection = async () => {
  const state = await NetInfo.fetch();

  console.log('Connected?', state.isConnected);
  console.log('Type:', state.type);
};

Listen for Changes

// Watch the road continuously
useEffect(() => {
  const unsubscribe = NetInfo.addEventListener(
    (state) => {
      if (state.isConnected) {
        console.log('Road is open!');
      } else {
        console.log('Road is closed!');
      }
    }
  );

  // Stop watching when done
  return () => unsubscribe();
}, []);

Connection Types

Type Meaning
wifi Connected to WiFi
cellular Using mobile data
none No connection
unknown Can’t tell

🔌 Offline Detection: When the Lights Go Out

When there’s no internet, your app should still work! This is called offline mode.

The Offline Strategy

graph TD A["📱 User Action"] --> B{Online?} B -->|Yes| C["🌐 Send to Server"] B -->|No| D["📦 Save Locally"] D --> E["⏰ Wait for Internet"] E --> C

Building Offline Support

const saveData = async (data) => {
  const netState = await NetInfo.fetch();

  if (netState.isConnected) {
    // Online: send to server
    await fetch('/api/save', {
      method: 'POST',
      body: JSON.stringify(data)
    });
  } else {
    // Offline: save locally
    const queue = await AsyncStorage.getItem(
      'offlineQueue'
    ) || '[]';

    const items = JSON.parse(queue);
    items.push(data);

    await AsyncStorage.setItem(
      'offlineQueue',
      JSON.stringify(items)
    );
  }
};

Sync When Back Online

// When internet comes back
NetInfo.addEventListener(async (state) => {
  if (state.isConnected) {
    // Check if we have saved items
    const queue = await AsyncStorage.getItem(
      'offlineQueue'
    );

    if (queue) {
      const items = JSON.parse(queue);

      // Send each saved item
      for (const item of items) {
        await fetch('/api/save', {
          method: 'POST',
          body: JSON.stringify(item)
        });
      }

      // Clear the queue
      await AsyncStorage.removeItem(
        'offlineQueue'
      );
    }
  }
});

🎁 Putting It All Together

Here’s how all our helpers work as a team:

graph TD A["🔌 NetInfo"] -->|Check Road| B{Connected?} B -->|Yes| C["📬 Fetch API"] B -->|No| D["📦 AsyncStorage"] C -->|With| E["🔐 Auth Token"] C -->|Handle| F["🚨 Errors"] C -->|Can| G["✋ Cancel"] C -->|Upload| H["📁 Files"] D -->|Sync Later| C

Complete Example: Smart Data Fetcher

const smartFetch = async (url, options = {}) => {
  // 1. Check internet
  const net = await NetInfo.fetch();

  if (!net.isConnected) {
    // Try local cache
    const cached = await AsyncStorage.getItem(url);
    if (cached) return JSON.parse(cached);
    throw new Error('No internet & no cache');
  }

  // 2. Setup cancellation
  const controller = new AbortController();
  const timeout = setTimeout(
    () => controller.abort(),
    10000
  );

  try {
    // 3. Get auth token
    const token = await AsyncStorage.getItem(
      'authToken'
    );

    // 4. Make request
    const response = await fetch(url, {
      ...options,
      signal: controller.signal,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`
      }
    });

    // 5. Handle errors
    if (!response.ok) {
      throw new Error(`Error: ${response.status}`);
    }

    const data = await response.json();

    // 6. Cache result
    await AsyncStorage.setItem(
      url,
      JSON.stringify(data)
    );

    return data;
  } finally {
    clearTimeout(timeout);
  }
};

🌟 Key Takeaways

Helper Job Remember
Fetch API Send/receive data The mailman
Error Handling Handle problems Always use try/catch
AbortController Cancel requests Stop sign
Auth Token Prove identity VIP pass
File Upload Send big files Use FormData
AsyncStorage Remember things Memory box
NetInfo Check connection Road inspector
Offline Mode Work without internet Save locally first

🚀 You Did It!

Now your app can:

  • ✅ Talk to servers
  • ✅ Handle problems gracefully
  • ✅ Cancel when needed
  • ✅ Prove who it is
  • ✅ Send and receive files
  • ✅ Remember things forever
  • ✅ Know when internet is available
  • ✅ Work offline

Your app is now a networking superhero! 🦸‍♂️

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.