Before we can start using axios and react-request-hook, we have to set up an axios instance and a RequestProvider component.
Let's get started setting up the libraries:
- First, we install the libraries:
> npm install --save react-request-hook axios
- Then, we import them in src/index.js:
import { RequestProvider } from 'react-request-hook'
import axios from 'axios'
- Now, we define an axios instance, where we set the baseURL to http://localhost:3000/api/—our backend server:
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000/api/'
})
In the config for our axios instance, we can also define other options, such as a default timeout for requests, or custom headers. For more information, check out the axios documentation: https://github.com/axios/axios#axioscreateconfig.
- Finally, we wrap our <App /> component with the <RequestProvider> component. Remove the following line of code:
ReactDOM.render(<App />, document.getElementById('root'));
Replace it with this code:
ReactDOM.render(
<RequestProvider value={axiosInstance}>
<App />
</RequestProvider>,
document.getElementById('root')
)
Now, our app is ready to use Resource Hooks!