Skip to content
Ben Foley edited this page Sep 1, 2019 · 1 revision

Let's get some data from an API

  1. Make the app, cd into it.
npx create-react-app react-axios
cd react-axios
code .
yarn start

code . will open the project in Visual Studio Code, don't do this if you don't have VS Code installed.

yarn start will launch the project in a browser.

  1. Clear out unused files
rm src/App.test.js src/App.css src/logo.svg
  1. Install axios
yarn add axios
  1. Add axios code to App.js
  • First, import axios
  • Then change the functional component into a class component
  • Create a state object, with a property to hold the API data
  • Use the componentDidMount lifecycle hook to make the API call, using axios
  • For a successful axios request, update the state items property
  • in the render method, loop over the items using Javascript map and display
import React from 'react'
import axios from 'axios'

class App extends React.Component {

  state = {
    items: []
  }

  componentDidMount() {
    const url = 'http://jsonplaceholder.typicode.com/users/'
    axios.get(url)
      .then(response => {
        this.setState({ items: response.data })
      })
  }

  render() {
    return (
      <ul>
        {
          this.state.items.map(item => {
            return (
              <li
                className="item"
                key={item.name}>
                  {item.name}
              </li>
            )
          })
        }
      </ul>
    )
  }
}

export default App;

Further reading

https://www.telerik.com/blogs/dealing-with-cors-in-create-react-app

Clone this wiki locally