Repository navigation
6a api
Ben Foley edited this page Sep 1, 2019
·
1 revision
- 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.
- Clear out unused files
rm src/App.test.js src/App.css src/logo.svg
- Install axios
yarn add axios
- 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
componentDidMountlifecycle 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;
https://www.telerik.com/blogs/dealing-with-cors-in-create-react-app