React Hooks The Perfect way to fetch data(s)

SanjayKhanSSK
3 min readFeb 15, 2020

--

If you are making large scale app , Follow this way.

Photo by Caspar Camille Rubin on Unsplash

8 bit story:

I’m building a Web APP called Sharly , this how i used Hooks to fetch API’s.

Lets begin ,

First copy paste code and see the explaination

create file fetchApi.js

async function EndPoint(props , setState){const HOST ="http://localhost:5000/"+props.surl;const HEADERS =  new Headers({
Accept:"application/json",
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"*",
})
const requestOptions = {
headers:HEADERS,
method : props.method,
}
if( requestOptions["method"] != "GET"){
requestOptions["body"] = props.body
}
const response_form = await fetch(HOST , requestOptions).then(respose=res.json()).
then(response => {setState(response)
}).catch(error => console.log("sorry error" , error ))
}
export default EndPoint;

— — —

create filePingPage.js

import React , {useState, useEffect, Fragment} from "react"
import EndPoint from "fetchApi"
function Ping(props){const [data , setData] = useState({surl:"ping" , method:"GET" ,isLoading:true , datas:{} ,message:"" , body:{} });const [response , setResponse] = useState();useEffect(()=>{EndPoint(data , setResponse)
console.log("response" , response)
return response
},[])return(
<Fragment>
<h1>View Console </h1>
{console.log( "response" , response)}{response != undefined ? <h1>{response.message}</h1> : ""}
</Fragment>
)}
export default Ping

Explanation:

Lets go in mixed way PingPage.js with fetchApi.js

Explanation for PingPage.js

import React , {useState, useEffect, Fragment} from "react"

Basic Import needed to create a hook function React.

import EndPoint from "fetchApi"

The File we have created before this.

function Ping(props){ // function declaration//let's create a Hook-state
const [data , setData] = useState({surl:"ping" , method:"GET" ,isLoading:true , datas:{} ,message:"" , body:{} });
//surl -> Specific URL to call// method -> method of that url// isLoading -> to display some loading widgets like spiner or bar etc.//datas , message , bosy -> Don't know why i added that , if you don't want delete it.

Creating another state to to store response

const [response , setResponse] = useState();

Calling the Fetch file in useEffect()

useEffect(()=>{ // Calling useEffectEndPoint(data , setResponse) //Calling the API file to get response with props => data and setState function => setResponse

Explanation for fetchApi.js

async function EndPoint(props , setState){ //function declaration
// called from PingPage.js EndPoint(data , setResponse)

URL:

const HOST ="http://localhost:5000/"+props.surl;
// "Host of my server" + "ping"

Headers:

const HEADERS =  new Headers({
Accept:"application/json",
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"*",
})
//Your backend error server accepts some headers , CORS etc..

RequestOptions:

const requestOptions = {
headers:HEADERS,
method : props.method,
}
//The basic requirement to call API

Body:

//Note that GET method won't accept BODY.
if( requestOptions["method"] != "GET"){
requestOptions["body"] = props.body
}

Calling the API

const response_form = await fetch(HOST , requestOptions).then(respose=res.json()).//Calling tha APIthen(response => {setState(response)
//storing the response to the passed setState function in our case it's `setResponse`
}).catch(error => console.log("sorry error" , error ))
// catching the Error.
}
export default EndPoint

Back to PingPage.js

// we called the Endpoint above this.
console.log("response" , response) //printing response
},[])
return(
<Fragment>
<h1>View Console </h1>
{response != undefined ? <h1>{response.message}</h1> : ""}//in my response there's a key called message it will show there.
</Fragment>
)}
export default Ping

Thank You:-

Links for some random Javascript stuffs.

If you want use Electron a simple way to connect Electron with python.

My channel

If you want to learn React Hooks , I think this Playlist will be useful.

Not My channel

Control your website with voice

My Channel

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response