Using the API

Last edit: 2025-01-03

For the front-end, I decided to use Axios instead of JavaScript's built-in fetch API. I find Axios to be more user-friendly and easier to use.

I have pre-configured axios in /utils/axios.ts to automatically use the BACK_END_URL, and if a token is present to automatically include that token in any request header.

I renamed this function 'api' so its sounds more like plain English.

So when you want to POST, you would write api.post("/api/", {body}) or when you want to GET, you would write api.get("/api/")

Heres an example of how to fetch some data from the back-end using axios:

example.tsx

import api from "@/utils/axios";
import { useEffect, useState } from "react";
 
const Example = () => {
  const [data, setData] = useState(null);
 
  useEffect(() => {
    api
      .get("/api/")
      .then((res) => {
        setData(res.data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);
 
  return (
    <div>
      {data ? (
        <div>
          <h1>{data.title}</h1>
          <p>{data.body}</p>
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};