DEV Community

Cover image for Very Simple way to handle requests
mmvergara
mmvergara

Posted on

Very Simple way to handle requests

How do you handle fetching in frontend?.... it's a pain right?

When i tried supabase i liked how they handle their request

const { data, error } = await supabaseRequest()

if (error) {
// handle error
 return
}
// since there is not an error
// intellisense will show that data cannot be null 
console.log(data)
Enter fullscreen mode Exit fullscreen mode

IT'S SO SIMPLE!!!
IT'S SO SIMPLE!!!

So I tried replicating the structure but with my own backend and using axios in the frontend


1st Step

Make sure you are returning { data, error} in the backend

export const createProduct = async (req: Req, res: Res) => {
  try {
    const newProd = await saveProductDb(req.body);

    return res.status(201).json({ data: newProd, error: null });
  } catch (error) {
    return res.status(400).json({ data: null, error: error.message });
  }
};

Enter fullscreen mode Exit fullscreen mode

2nd step ( optional, probably )

Initialize Axios Instance / Interceptors

// Initialize Axios Instance
axios.defaults.withCredentials = true;
const AxiosInstance = axios.create({
  baseURL: BASE_URL,
  withCredentials: true,
});

AxiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    // You can handle errors here
    toast({
      title: error.response.data.error,
      status: "error",
      position: "top-right",
    });
    console.log(error);
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

3rd step

Initiliaze Types, this is for the intellisense in the responses

// Initialize Types
type ApiRes<T> = {
  data: T | null;
  error: string | null;
};

type AxiosParsedResponse<T> =
  | { data: null; error: AxiosError<ApiRes<T>> }
  | {
      data: T;
      error: null;
    };
Enter fullscreen mode Exit fullscreen mode

4th step

Create your Get,Post,Etc axios instances

export const AxiosGet = async <T>(
  url: string
): Promise<AxiosParsedResponse<T>> => {
  try {
    const res = await AxiosInstance.get<ApiRes<T>>(url);
    return { data: res.data.data!, error: null };
  } catch (err) {
    const error = err as AxiosError<ApiRes<T>>;
    return { data: null, error: error };
  }
};
Enter fullscreen mode Exit fullscreen mode

in this example we're using get.

DONE!

export const Register = async (userData: RegisterFields) => {
  const { data, error } = await AxiosPost<UserData>("/auth/register", userData);
  // data can be null
  if (error) return;

  // intellisense shows data is not null
  console.log(data);
};
Enter fullscreen mode Exit fullscreen mode

There is probably a better way out there to do this please do comment, i want to learn and there are probably more ways to handle request better than this, but i just want to share this because it works for me.

Thanks for reading!

SAMPLE IMPLEMENTATION

Top comments (0)