Copy export default function useFetch (){
async function getData (url) {
const res = await fetch ( ` ${ url } ` );
const result = await res .json ();
const responseStatus = res .status;
return [result , responseStatus];
}
async function postData (url , data) {
const res = await fetch ( ` ${ url } ` , {
method : "POST" ,
body : JSON .stringify (data) ,
headers : {
"Content-type" : "application/json; charset=UTF-8"
}
});
const result = await res .json ();
const responseStatus = res .status;
return [result , responseStatus];
}
async function updateData (url , data) {
const res = await fetch ( ` ${ url } ` , {
method : "PUT" ,
body : JSON .stringify (data) ,
headers : {
"Content-type" : "application/json; charset=UTF-8"
}
});
const result = await res .json ();
const responseStatus = res .status;
return [result , responseStatus];
}
async function deleteData (url) {
const res = await fetch ( ` ${ url } ` , {
method : "DELETE"
});
const result = await res .json ();
const responseStatus = res .status;
return [result , responseStatus];
}
return [getData , postData , updateData , deleteData];
}
Copy // App.css
.m - 2 {
margin : 2rem;
}
// App.jsx
import { Button , useFetch } from "../../index.js"
import "./App.css"
function App () {
const [ getData , postData , updateData , deleteData ] = useFetch ();
async function getClick () {
const [ result , responseStatus ] = await getData ( "https://farzi-vichar-api.vercel.app/language/hindi/random" );
console .log (result , responseStatus);
}
async function postClick () {
const [ result , responseStatus ] = await postData ( "https://jsonplaceholder.typicode.com/posts" , {
title : 'foo' ,
body : 'bar' ,
userId : 1 ,
})
console .log (result , responseStatus);
}
async function putClick () {
const [ result , responseStatus ] = await updateData ( "https://jsonplaceholder.typicode.com/posts/1" , {
id : 1 ,
title : 'foo' ,
body : 'bar' ,
userId : 1 ,
});
console .log (result , responseStatus);
}
async function deleteClick () {
const [ result , responseStatus ] = await deleteData ( "https://jsonplaceholder.typicode.com/posts/1" );
console .log (result , responseStatus);
}
return (
<>
< Button buttonText = "Get" onClickFunction = {getClick} userButtonStyle = { "m-2" }></ Button >
< Button buttonText = "Post" onClickFunction = {postClick} userButtonStyle = { "m-2" }></ Button >
< Button buttonText = "Update" onClickFunction = {putClick} userButtonStyle = { "m-2" }></ Button >
< Button buttonText = "Delete" onClickFunction = {deleteClick} userButtonStyle = { "m-2" }></ Button >
</>
)
}
export default App