Skip to content

Instantly share code, notes, and snippets.

@MansourM61
Last active January 15, 2026 14:45
Show Gist options
  • Select an option

  • Save MansourM61/3cc4cd301d6e1972cf5fe0674772a2ad to your computer and use it in GitHub Desktop.

Select an option

Save MansourM61/3cc4cd301d6e1972cf5fe0674772a2ad to your computer and use it in GitHub Desktop.

Client Fetching

Native fetch

JS (browser and Node.js) provides built-in fetch function.

Fetching Data (GET)

async function getData() {
  const url = "given URL";

  const queryURL = new URL("given route", url);

  queryURL.searchParams.append("par1", val1);
  queryURL.searchParams.append("par2", val2);
  queryURL.searchParams.append("par3", val3);

  const url = queryURL.href;

  let result;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }

    result = await response.json();
    console.log(result);
  } catch (error) {
    console.error(error.message);
  }

  return result;
}

Sending Data (POST)

async function getData() {
  const url = "given URL";
  const queryURL = new URL("given route", url);

  queryURL.searchParams.append("par1", val1);
  queryURL.searchParams.append("par2", val2);
  queryURL.searchParams.append("par3", val3);

  const url = queryURL.href;

  let result;
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }

    result = await response.json();
  } catch (error) {
    console.error(error.message);
  }

  return result;
}

AXIOS

Axios is a wrapper around fetch, offering advanced features.

To install:

npm install axios

upfetch

upfetch is a fetch client builder with schema validation. It can be a replacement for axios

To install:

npm i up-fetch

Fetching Data

import axios from "axios";

// Make a request for a user with a given ID
axios
  .get("given URL/?par1=val1")
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios
  .get("given URL", {
    params: {
      par1: val1,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get("given URL");
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Sending Data

axios
  .post("given URL", formData)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Fetching Data (GET) in React

import { useEffect, useState } from "react";
import { up } from "up-fetch";

const upfetch = up(fetch);

function App() {
  const [results, setResults] = useState([]);

  useEffect(() => {
    let ignore = false;

    async function loadData() {
      const data = await upfetch("https://jsonplaceholder.typicode.com/users");
      if (!ignore) {
        setResults(data);
      }
    }

    loadData();

    return () => {
      ignore = true;
    };
  }, []);

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {results.map((s: { name: string }, i) => {
        return <div key={i}>{s.name}</div>;
      })}
    </div>
  );
}

export default App;

Validating Data

import { up, isValidationError } from "up-fetch";
import { z } from "zod";

const upfetch = up(fetch, () => ({
  onRequest: (options) => {
    // Called before the request is made, options might be mutated here
  },
  onSuccess: (data, options) => {
    // Called when the request successfully completes
  },
  onError: (error, options) => {
    // Called when the request fails
  },
}));

try {
  const data = await upfetch(
    // These parameters are set for this individual upfetch
    // To set the parameters for all upfetch instances, move them
    // to `up()` function's callback definition.
    "given URL",
    {
      attempts: 3,
      timeout: 30000, // request timeout
      delay: 1000, // delay between each attempt
      method: "POST",
      body: formData,
      params: {
        par1: val1,
        par2: val2,
        par3: val3,
      },
      schema: z.object({
        id: z.number(),
        //...
      }),
    }
  );
} catch (error) {
  if (isValidationError(error)) {
    console.log(error.issues);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment