Swapi using React

API Calling in React with SWAPI (Star Wars API)

🌐 API Calling in React with SWAPI (Star Wars API)

One of the coolest things you can do in React is call real-world APIs and show live data! In this post, we’ll use the famous Star Wars API (SWAPI) to learn how to fetch and display data in a React app.

🧠 What is an API?

API stands for Application Programming Interface. It’s a way for applications to talk to each other. For example, a weather app fetches real-time weather from a server using an API.

🚀 What is SWAPI?

SWAPI (swapi.dev) is a free API that provides data from the Star Wars universe—people, planets, films, and more.

Example URL: https://swapi.dev/api/people/1 gives data about Luke Skywalker!

📦 Using fetch() in React

React doesn’t have built-in API tools, but JavaScript’s fetch() works perfectly. We'll use useEffect and useState to fetch data when the component loads.

🧪 Simple Example: Fetch Luke Skywalker’s Info

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

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

  useEffect(() => {
    fetch('https://swapi.dev/api/people/1/')
      .then(response => response.json())
      .then(data => setCharacter(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>Mass:</strong> {character.mass} kg</p>
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default StarWarsCharacter;

Explanation:

  • useState is used to store the character data.
  • useEffect runs once when the component loads (because of the empty []).
  • fetch() calls the API and updates state when the data is received.
  • We use conditional rendering to show “Loading...” until data is fetched.

🌌 Try These Variations

  • Try https://swapi.dev/api/people/4 for Darth Vader
  • Display a list of people using https://swapi.dev/api/people
  • Create a dropdown to select characters

💡 Summary

  • APIs let you fetch live data from the internet.
  • SWAPI is a fun API to practice with.
  • useEffect + fetch() + useState = dynamic React apps!

🎯 Happy coding! You’ve just taken your first step into the React Galaxy 🚀

Post a Comment

0 Comments

Me