Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fixes #37
  • Loading branch information
bmullan91 committed Feb 26, 2019
commit ac74879a1a3ac6e16e1d21af5aa7c224606a7b87
20 changes: 18 additions & 2 deletions src/useClientRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ const React = require('react');
const ClientContext = require('./ClientContext');

const actionTypes = {
RESET_STATE: 'RESET_STATE',
LOADING: 'LOADING',
CACHE_HIT: 'CACHE_HIT',
REQUEST_RESULT: 'REQUEST_RESULT'
};

function reducer(state, action) {
switch (action.type) {
case actionTypes.RESET_STATE:
return action.initialState;
case actionTypes.LOADING:
if (state.loading) {
return state; // saves a render cycle as state is the same
Expand All @@ -18,6 +21,11 @@ function reducer(state, action) {
loading: true
};
case actionTypes.CACHE_HIT:
if (state.cacheHit) {
// we can be sure this is the same cacheKey hit
// because we dispatch RESET_STATE if it changes
return state;
}
return {
...action.result,
cacheHit: true,
Expand Down Expand Up @@ -53,11 +61,19 @@ function useClientRequest(query, initialOpts = {}) {
const cacheKey = client.getCacheKey(operation, initialOpts);
const initialCacheHit =
initialOpts.skipCache || !client.cache ? null : client.cache.get(cacheKey);
const [state, dispatch] = React.useReducer(reducer, {
const initialState = {
...initialCacheHit,
cacheHit: !!initialCacheHit,
loading: initialOpts.isMutation ? false : !initialCacheHit
});
};
const [state, dispatch] = React.useReducer(reducer, initialState);

// NOTE: state from useReducer is only initialState on the first render
// in subsequent renders the operation could have changed
// if so the state would be invalid, this effect ensures we reset it back
React.useEffect(() => {
dispatch({ type: actionTypes.RESET_STATE, initialState });
}, [JSON.stringify(cacheKey)]);

// arguments to fetchData override the useClientRequest arguments
async function fetchData(newOpts) {
Expand Down