Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a hook-based implementation of query #73

Open
dlikhten opened this issue Jul 31, 2019 · 0 comments
Open

Create a hook-based implementation of query #73

dlikhten opened this issue Jul 31, 2019 · 0 comments

Comments

@dlikhten
Copy link

dlikhten commented Jul 31, 2019

Here's one attempt I made at making a hook. Works quite nicely. I think this could be quite a nice addition to this library.

import _ from 'lodash-es';
import { useCallback, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getRequestInfo, invalidateRequests } from 'redux-bees';

export const useQueryWithInitialFetch = (apiCall, args) => {
  const queryResult = useQuery(apiCall, args);
  const [, , fetch] = queryResult;

  useEffect(() => {
    fetch({ invalidate: false });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return queryResult;
};

export const useQuery = (apiCall, args) => {
  const dispatch = useDispatch();

  const requestInfo = useSelector(state => getRequestInfo(state, apiCall, [args]), _.isEqual);

  const fetch = useCallback(
    (options = {}) => {
      const { invalidate = false } = options;

      return (async () => {
        if (invalidate) {
          await dispatch(invalidateRequests(apiCall, args));
        }
        return dispatch(apiCall(args));
      })();
    },
    // stringify the args so they can be trivially compared. Two args that are effectively identical shouldn't
    // cause a fetch re-creation, otherwise two { } objects would actually cause a diff here and indicate to the
    // caller that there is a new fetch to execute on...
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [dispatch, apiCall, JSON.stringify(args)]
  );
  const invalidateAll = useCallback(() => dispatch(invalidateRequests(apiCall)), [dispatch, apiCall]);

  return [requestInfo.result, { ..._.omit(requestInfo, 'results') }, fetch, invalidateAll];
};

use case:

const [ terms, setTerms ] = useState('');
const [data, status, fetch, invalidateAll] = useQuery(api.theCall, { 'filter[name]': terms });

// this gets updated when terms changes because fetch gets re-created
useEffect(() => {
  fetch();
}, [fetch]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant