Black Friday Sale Upgrade Your Home →

Fetch Data from an HTTP Server

Fetch Data from an HTTP Server in a React Native Application using fetch or axios

In this lesson we’ll use fetch to get data from an HTTP server, and store it in state in our React Native application. fetch works almost identically on the web and React Native - with the possible exception of how it handles cookies. We’ll also take a look at axios - which is an alternative to fetch.

Lifecycle methods and Hooks

The same React class-based lifecycle methods - componentDidMount, render, componentWillUnmount etc - and hooks - useState, useEffect etc - exist for React Native.

JSX
class MyComponent extends Component {
componentDidMount() {
// setup things - fetch data etc
}
render() {
// render data to screen
}
componentWillUnmount() {
// cleanup things - cancel promises, clear timeouts etc
}
}
JSX
const MyComponent = () => {
useEffect(() => {
// setup things
return () => {
// cleanup things
}
}, [])
return (
// render things
)
}

Fetching data

The same fetch API that exists in web-land is also available in React Native. Additionally, any other HTTP request libraries can be installed from NPM - such as axios. Axios provides a slightly more declarative and clearer API than fetch, but either can be used for this course.

BASH
npm i axios
JSX
import axios from 'axios'
class Pokedex extends Component {
state = {}
const url = 'https://pokeapi.co/api/v2/pokemon/'
componentDidMount() {
axios.get(url)
.then(({ data }) => this.setState({ pokemon: data }))
}
render() {
return this.state.pokemon.map(p => <Text>{p.name}</Text>)
}
}

Or using a <FlatList /> component.

JSX
import axios from 'axios'
class Pokedex extends Component {
state = {}
const url = 'https://pokeapi.co/api/v2/pokemon/'
componentDidMount() {
axios.get(url)
.then(({ data }) => this.setState({ pokemon: data }))
}
render() {
return <FlatList
data={this.state.pokemon}
renderItem={({ item }) => <Text>{item.name}</Text>}
keyExtractor={pokemon => pokemon.id}
/>
}
}

🐦   Previous   💼   Next