Mark As Completed Discussion

Making API Requests

When working with APIs in React, you can make API requests using libraries like fetch or axios. These libraries provide convenient methods for sending HTTP requests and handling the responses.

Here's an example of making an API request using the axios library:

JAVASCRIPT
1const axios = require('axios');
2
3axios.get('https://api.example.com/data')
4  .then(response => {
5    console.log(response.data);
6  })
7  .catch(error => {
8    console.error(error);
9  });

In this example, the axios library is used to send a GET request to the specified URL. The response is then accessed using the .data property of the response object, and logged to the console.

You can also make API requests using the fetch function in JavaScript. Here's an example using fetch:

JAVASCRIPT
1fetch('https://api.example.com/data')
2  .then(response => response.json())
3  .then(data => {
4    console.log(data);
5  })
6  .catch(error => {
7    console.error(error);
8  });

In this example, the fetch function is used to send a GET request to the specified URL. The response is then parsed as JSON using the .json() method, and the resulting data is logged to the console.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment