Skip to content
Closed
Changes from all commits
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
24 changes: 21 additions & 3 deletions src/useClientRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,31 @@ 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
// saves a render cycle as state is the same
return state;
}
return {
...state,
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 +62,20 @@ 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