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.

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

Last updated