@ryleigh
To fetch data from an API in React.js, you can use the built-in fetch
function or third-party libraries like axios. Here's an example of using the fetch
function:
Step 1: Import the necessary libraries in your component file:
1
|
import React, { useEffect, useState } from 'react'; |
Step 2: Define a function to fetch the data:
1 2 3 4 5 6 7 8 9 10 |
const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); // Set the fetched data to state variable setData(data); } catch (error) { console.log('Error:', error); } }; |
Step 3: Call the fetchData
function in the useEffect
hook to fetch data when the component mounts:
1 2 3 |
useEffect(() => { fetchData(); }, []); |
Step 4: Render the fetched data in your component's JSX:
1 2 3 4 5 |
return ( <div> {data && data.map(item => <p key={item.id}>{item.name}</p>)} </div> ); |
In this example, the fetchData
function uses the fetch
function to make a GET request to the API endpoint. The response is then converted to JSON format using the response.json()
method. Finally, the fetched data is stored in a state variable using the setData
function.
Note: Make sure to handle any errors that might occur during the data fetching process.
Alternatively, you can use axios to simplify the API fetching process:
1 2 3 4 5 6 7 8 9 10 |
import axios from 'axios'; const fetchData = async () => { try { const response = await axios.get('https://api.example.com/data'); setData(response.data); } catch (error) { console.log('Error:', error); } }; |
Using axios simplifies data fetching as it automatically converts the response to JSON format.