bsoc-bitbyte / busify

A centralised bus ticket booking system that will allow the students to book tickets in advance through an online website, saving time and effort.
https://busify.vercel.app
34 stars 70 forks source link

[Feature Request]: react custom hook for data fetching #38

Closed prajjwalkapoor closed 8 months ago

prajjwalkapoor commented 1 year ago

Is your feature request related to a problem? Please describe.

Currently, we are writing repetitive code for data fetching which violates the DRY principle.

Describe the solution you'd like

Make a react custom hook something like useFetch for data fetching. Make sure you will handle the method, URL ( Fix the host and fetch it from env, just change the path ), allowCookie, payloads etc. You should use Axios for fetching.

Describe alternatives you've considered

No response

Developer Help

No response

RISHIKESHk07 commented 1 year ago

@prajjwalkapoor i would like to contribute to this issue

prajjwalkapoor commented 1 year ago

Sure, go ahead @RISHIKESHk07

prajjwalkapoor commented 1 year ago

any updates @RISHIKESHk07?

RISHIKESHk07 commented 1 year ago

@prajjwalkapoor I been working on the issue ,had problem with backend on docker ,retrying the process with linux as of now

RISHIKESHk07 commented 1 year ago
import { useEffect, useState } from 'react';
import axios from 'axios';

const useFetch = (method, path, allowCookie = false, payload = null) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const url = `PATH`

        const options = {
          method,
          url,
          withCredentials: allowCookie,
          data: payload,
        };

        const response = await axios(options);
        setData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [method, path, allowCookie, payload]);

  return { data, loading, error };
};

export default useFetch;

this the solution i came up with

RISHIKESHk07 commented 1 year ago

@prajjwalkapoor where should this change go.