use-http icon indicating copy to clipboard operation
use-http copied to clipboard

Is it safe to reuse response?

Open AlissonRS opened this issue 4 years ago • 0 comments

I'm creating a custom hook for reusable http requests, it looks like below (shortened for the sake of simplicity):

import { useCallback } from 'react';
import useFetch from 'use-http';

export const useMyNiceService = () => {
  const { post, put, response } = useFetch();

  const add = useCallback(
    async (user: any) => {
      const result = await post('/user', user);
      return { result, response };
    },
    [post, response]
  );

  const edit = useCallback(
    async (user: any) => {
      const result = await put('/user', user);
      return { result, response };
    },
    [put, response]
  );

  return {
    add,
    edit
  };
}

In case you're wondering why I wrap my methods in useCallback, it's because in my function components these reusable methods are called inside useEffect and need to be added as a dependency, so useCallback is required to avoid infinite loop.

I return response within my add and edit methods alongisde the result, so the caller can check the response status, headers, etc, and potentially all of my reusable methods will need response as a dependency. So I just wanted to make sure I'm not misusing this, I'm concerned that every time the response object changes, this will recreate my reusable methods (e.g add, edit) as response is a dependency, and this seems odd to me because it doesn't make sense the functions being recreated, but I'm not sure if this is the React way of doing this. So here are my questions:

1 - Is it ok to use response as a dependency to useCallback? Is there a better way of reusing code that need useFetch? 2 - Is it ok to reuse response in multiple methods (e.g add, edit, gets), as the codebase grows we may have two gets being called in parallel using the same response, that seems wrong to me.

Thanks, this is a great library and I'm enjoying it!!!

AlissonRS avatar May 11 '21 04:05 AlissonRS