Hey Y'all!
In this episode of React, What's That?!, We'll be discussing the simple use of a hook known as useEffect to help us run a side effect that will fetch us data from an API.
The fetch request that we will be using is called a GET request and it is used to simply get data from an API. The setup for a GET request is simple and straightforward. But before we "gets to GET'n", let's talk about useEffect.
First, what is useEffect. If you search the definition, you will find that useEffect is a Hook that allows you to perform side effects in your functional components. Ah, but what is a side effect, you ask? Well, side effects are, according to the internet, actions that affect something outside the scope of your component, like: Fetching data from an API, Updating the DOM directly, Setting up subscriptions or timers, and Interacting with browser APIs. Great!!
So first, let's establish what we want to do. How about render data from an API to the DOM. Simple yet elegant.
Step 1. import { useEffect, useState } from 'react'
Step 2. create your function.
function MyComponent() {
return()
}
Step 3. create the variables that will set the state.
function MyComponent() {
const [data, setData] = useState([])
return()
}
Step 4. useEffect!
function MyComponent() {
const [data, setData] = useState([])
useEffect(() => {
const fetch('example https://api')
.then((response)=>
response.json())
.then((data)=> setData(data)
}, [])
How does useEffect work?
It takes two arguments:
A function that contains the side effect logic.
An optional dependency array.
The function runs after every render by default, but you can control when it runs using the dependency array.
If the dependency array is empty, the effect runs only once after the initial render.
If the dependency array contains values, the effect runs whenever one of those values changes.
In React, when you call a function like setData, you're typically using a state setter function provided by the useState hook. This function updates the state of a component, and React re-renders the component to reflect the new state.
Once that data has been fetched, then you will want to render the data to your DOM by using the Map() method within the return().
Step 5. Render to the DOM.
return(
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
)
If the data from the API has different key:value pairs, then you can render those different values using the, "item" object. Item.description, if there is a description, item.price, if there is a price, and so on.
This basic setup will render the data that was fetched from the API to your DOM. You can then use CSS to style it how you would like.
Rendering data to your DOM from an API really can't be simpler.
Cheers!
Top comments (0)