React and React native API — Fetch Template

SanjayKhanSSK
2 min readNov 29, 2020

Use this template and focus on your components not on your fetching

Photo by Rodion Kutsaev on Unsplash

props.surl => “api-url”

body => “JSON” or “Media”

setState => Sets response to state

setError => Sets Error to state

mediaUpload => Bool => True if uploading any media, False if not uploading any media

Make sure you’re calling this function from useEffect.

async function EndPoint(props  , body, setState , setError , mediaUpload=false){
const DEV = false
let HOST = "https://api.app.in/"+props.surlif (DEV == true){HOST ="http://localhost:5000/"+props.surl;// HOST ="http://localnetworkhost:5000/"+props.surl;}let HEADERS = {}switch(mediaUpload ){case true:HEADERS = {Accept: "application/json","user-access-token":localStorage.getItem("user-access-token")}breakdefault:HEADERS = {Accept:"application/json","Content-Type":"application/json","Access-Control-Allow-Origin":"*","user-access-token":localStorage.getItem("user-access-token")}}const requestOptions = {headers:HEADERS,method : props.method,}if( requestOptions["method"] != "GET" && mediaUpload == false){requestOptions["body"] = JSON.stringify(body)}if(mediaUpload == true){requestOptions["body"] = body
// passing raw body (images,videos)
}var response = undefined;const response_form = await fetch(HOST , requestOptions).then(handleResponse).then(response => {setState(response)}).catch((error) =>{ error.then((e) => {setError(e) ;}) })function handleResponse(response){if (!response.ok){if(response.status == 403){// Payment Required
throw response.json() ;
// throw custom json
}else{//throw custom json
throw response.json();
}}else{return response.json();}}}export default EndPoint;

--

--