Swapi using localstorage in React

Using SWAPI in React with localStorage

🚀 Using SWAPI in React with localStorage

In this blog post, we'll learn how to use the Star Wars API (SWAPI) in a React app and store the fetched data in localStorage. This way, we can avoid unnecessary API calls and make our app faster.

🧠 What is localStorage?

localStorage is a built-in feature in browsers that allows you to store small amounts of data. The data stays even if you close or refresh the page.

🌐 What is SWAPI?

SWAPI is a free API that gives information about Star Wars characters, films, planets, and more.

Example endpoint: https://swapi.dev/api/people/1 returns data about Luke Skywalker.

📦 Our Goal

  • First, try to get the character data from localStorage.
  • If not found, fetch it from the API.
  • Then save the fetched data to localStorage.
  • Finally, display it in the app.

🧪 Complete React Example

import React, { useState, useEffect } from 'react';

function StarWarsCharacter() {
  const [character, setCharacter] = useState(null);

  useEffect(() => {
    const savedData = localStorage.getItem('character1');

    if (savedData) {
      console.log('Loaded from localStorage');
      setCharacter(JSON.parse(savedData));
    } else {
      console.log('Fetching from API...');
      fetch('https://swapi.dev/api/people/1/')
        .then(response => response.json())
        .then(data => {
          setCharacter(data);
          localStorage.setItem('character1', JSON.stringify(data));
        });
    }
  }, []);

  return (
    <div>
      <h2>Star Wars Character</h2>
      {character ? (
        <div>
          <p><strong>Name:</strong> {character.name}</p>
          <p><strong>Height:</strong> {character.height} cm</p>
          <p><strong>Birth Year:</strong> {character.birth_year}</p>
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default StarWarsCharacter;

Key Points:

  • localStorage.getItem() checks if data is already saved.
  • JSON.parse() converts stored text back to an object.
  • If not found, we fetch data and use localStorage.setItem() to save it.

📦 Try Different Characters

  • Try people/4 for Darth Vader
  • Use dropdowns or buttons to let users choose characters
  • Store each character using a unique key like character4, character5, etc.

💡 Summary

  • localStorage helps reduce unnecessary API calls
  • You can store and retrieve data using setItem() and getItem()
  • This technique improves performance and makes apps feel faster

⚡ Give it a try in your next project and feel the difference in speed!

Post a Comment

0 Comments

Me