DEV Community

David Bell
David Bell

Posted on • Edited on • Originally published at davidbell.space

Build with the SWAPI Star Wars API, React with Hooks

Let’s make an app with the The Star Wars API. I want to create a simple app that gets data of characters and displays them in a list.

This is not a guide to React so familiarity with some React is essential. Think of this article as a ‘code along with me’ type thing. This is just how I'm going to create a quick little app.

Must include

  • fetch data from the API
  • set state using useState and useEffect hooks
  • Display the content in a list

Cleanup

I like to begin with create react app and delete the files I don’t need. Then create a components folder with the table display component. List.js.

import React from "react"

export const List = () => {
  return <h1>Hello List</h1>
}
Enter fullscreen mode Exit fullscreen mode

In App.js import List.js to check everything is working correctly.

import React from "react"
import { List } from "./components/List"

function App() {
  return (
    <div>
      <List />
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Fetching the Data

Create a folder called utils with the file api.js. This will have out API data fetching functions within.

Add the url endpoints:

const urls = [
  "https://swapi.co/api/people/1",
  "https://swapi.co/api/people/1",
  "https://swapi.co/api/people/2",
  "https://swapi.co/api/people/3",
  "https://swapi.co/api/people/4",
]
Enter fullscreen mode Exit fullscreen mode

Layout a try/catch async function. This is a good thing to start with because it lays it out for you explicitly. Basically the function will try to do something and if theres something wrong it will catch the error and log it to the console.

  export const fetchData = async () => {
      try {

      } catch (error) {
          console.log(Error, error)
      }
  }
Enter fullscreen mode Exit fullscreen mode

Now our try/catch is laid out let's add the rest. Then I’ll explain.

export const fetchData = async () => {
  try {
    const response = await Promise.all(
      urls.map(url => fetch(url).then(res => res.json()))
    );
    console.log(response);
    return response;
  } catch (error) {
    console.log(Error, error);
  }
};
Enter fullscreen mode Exit fullscreen mode
  • We create a variable response for holding our data.
  • Using the keyword await. Await - ‘Go do this for me and come back with what you get.’
  • Promise.all method is used to tell the function to go and do all of the urls from our urls array. One at a time.
  • Using .map() array method to iterate over our array.
  • We then pass each url into the fetch(). Seen as url => fetch(url)
  • We use .then for chaining. Taking the response or ‘res’ which is returned once ‘fetched’. Convert the response to JSON which we can use.

But we need to call this function in our app when the page is rendered to the screen. We do this using the useEffect hook from react. No if you check in the console you will see our Star Wars data logged.

import React, { useEffect } from "react"

import { List } from "./components/List"
import { fetchData } from "./utils/api"

function App() {
  useEffect(() => {
    fetchData()
  })

  return (
    <div>
      <List />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Setting State

Now we must create some state to use. We will do this with the useState hook.

import React, { useEffect, useState } from "react"

import { List } from "./components/List"
import { fetchData } from "./utils/api"

function App() {
  const [people, setPeople] = useState([])

  useEffect(() => {
    fetchData().then(response => setPeople(response))
  })

  return (
    <div>
      <Table />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode
  • We import useState from React
  • Create state as an empty array const [people, setPeople] = useState([])
  • Using .then once more for chaining. We get the response and set our state to the response .then(response => setPeople(response))

Now check your React dev tools and if followed correctly you will see the state is now Star Wars characters.

Now we have our people state we must pass it into our List component <List people={people} />

Display the Data

export const List = ({ people }) => {
  return (
    <div>
      <h1>List</h1>
      <ul>
        {people.map(person => {
          return <li key={person.name}>{person.name}</li>
        })}
      </ul>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode
  • We de-structure people { people }
  • using map() we iterate over our array 'people’ and for each person we display the name of the person as a list item.

And there we have a very very basic app displaying data from an API in React.

Conclusion

Though very basic maybe you could get some value out of this. There is lots more that can be done to extend this app further. Go ahead and add styles and use more data from the SWAPI API.

Let's connect

Twitter

Top comments (1)

Collapse
 
aedward317 profile image
Abby

Hello David,

"We use .then for chaining. Taking the response or ‘res’ which is returned once ‘fetched’. Convert the response to JSON which we can use."

I believe it actually converts the response to a JavaScript Object.

developer.mozilla.org/en-US/docs/W...