Http Requests
When it comes to executing http requests in React Native you have to use a library,
as there is nothing built-in like fetch
in the Web.
Depending on your backend (REST vs GraphQL) you would either go with Axios or Apollo Client.
Axios
To install just run npm i axios
and then import like so: import axios from 'axios';
.
Then you just have to create an instance which you can configure.
export default axios.create({
baseURL: 'http://localhost:3000'
});
The baseURL
-property above states that every request made with Axios
will prefix the path with this url.
E.g. axios.get('/some-path')
will actually be resolve as GET http://localhost:3000/some-path
.
Accessing Response Data
The actual response of a request is stored in the data
-property and can be accesses like that:
const response = await axios.get('/search', {
params: {
term: searchTerm,
limit: 50
}
});
const results = response.data;
Adding Authorization Header
You can easily add an Authorization
-header via an interceptor like so:
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const instance = axios.create({
baseURL: 'http://localhost:3000'
});
instance.interceptors.request.use(
async (config) => {
const token = await AsyncStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
Apollo Client
To install just run npm i @apollo/client graphql
and then import like so:
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
.
Now you have to create your ApolloClient instance:
const client = new ApolloClient({
uri: 'localhost:4000/graphql',
cache: new InMemoryCache()
});
And wrap your application with the ApolloProvider
like so:
const App = () => (
<ApolloProvider client={client}>
<MyRootComponent />
</ApolloProvider>
);
For more information study this page.