Skip to content

Instantly share code, notes, and snippets.

@warderer
Last active August 17, 2022 15:30
Show Gist options
  • Select an option

  • Save warderer/4bc778d05f7536ca3ad634663f02652d to your computer and use it in GitHub Desktop.

Select an option

Save warderer/4bc778d05f7536ca3ad634663f02652d to your computer and use it in GitHub Desktop.
[React API Call Template with Fetch] Boilerplate code for implementing generic API call with fetch in react projects #react #api #fetch
// This file usually is under API or Services folder.
export default async function apiCall(
url, {
method = "GET",
body,
headers = {}
}) {
try {
const response = await fetch(url, {
method,
body,
headers,
});
return await response.json();
} catch (error) {
Promise.reject(error);
}
}
import { useState } from 'react'
import apiCall from '../../apiCall'
const myComponent = () => {
const [apiData, setApiData] = useState([])
const getData = async () => {
try {
const URI = 'https://api.github.com/users/warderer' //Change the URL
const response = await apiCall(URI, { method: 'GET' }) // By default method is get
setApiData(response)
}
catch (error) {
setApiData([])
}
}
return (
<>
{apiData?.map((item, index) => (
<div key={index}>
<p>{item.name}</p>
</div>
))}
</>
)
}
export default myComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment