useFetch

The useFetch hook is a common hook provided by the Hartan library. This hook uses the native web Fetch API internally to fulfill the AJAX/HTTP requests done by the user.

This hook is a public hook and available for the users to use.

Code

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];
}

Explanation

  • As you can see above it uses the useFetch hook exposes for basic functions:

    • getData(url) -> uses the "GET" method on the provided url endpoint to fetch the data.

    • postData(url, data) -> uses the "POST" method on the provided url endpoint to submit the given data.

    • updateData(url, data) -> uses the "PUT" method on the provided URL endpoint to submit the given data.

    • deleteData(url) -> uses the "DELETE" method on the provided URL endpoint to delete the data.

  • All the functions above return two values, a result and a responseStatus respectively in the format return [result, responseStatus] .

Usage

// 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

Last updated