Last active
August 17, 2022 15:30
-
-
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 contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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