ūüŹ° Home

React Hooks: Manual Data Fetching and useState

Using the setState hook we can store data from fetch API and use it in our functional component. An example for this as follows:

import React, { useState } from "react"
import "./styles.css"

export default function App() {
  const [users, setUsers] = useState([])

  const fetchUsers = async () => {
    const fetchResponse = await fetch(
      "https://jsonplaceholder.typicode.com/users",
      { method: "Get" }
    )
    const fetchData = await fetchResponse.json()
    setUsers(fetchData)
  }

  return (
    <div className="App">
      <button onClick={fetchUsers}>Fetch Users</button>
      {users.map(user => (
        <p key={user.id}>{JSON.stringify(user)}</p>
      ))}
    </div>
  )
}

When we click on the Fetch Users button, it will run the fetchUsers async function. The function will store its Promise result in setUsers then the users variable will contain the data.

Reference: