Skip to content

Instantly share code, notes, and snippets.

@josephsavona
Created February 20, 2020 20:31
Show Gist options
  • Save josephsavona/79640eb59171b6b993378e57ab127999 to your computer and use it in GitHub Desktop.
Save josephsavona/79640eb59171b6b993378e57ab127999 to your computer and use it in GitHub Desktop.
// Somewhere, the Redux store needs to be wrapped in a mutable source object...
const mutableSource = createMutableSource(
relayEnvironment,
// Because the state is immutable, it can be used as the "version".
() => relayEnvironment.getVersion()
);
// It would probably be shared via the Context API...
const MutableSourceContext = createContext(mutableSource);
// Oversimplified example of how Redux could use the mutable source hook:
function useFragment(fragmentSelector) {
const mutableSource = useContext(MutableSourceContext);
const getSnapshot = useCallback(
store => store.lookup(fragmentSelector),
[fragmentSelector]
);
const subscribe = useCallback(
(store, handleChange) => {
return store.subscribe(
fragmentSnapshot, // <------- we need this result from getSnapshot
() => {
// The store changed, so let's get an updated snapshot.
const newSnapshot = getSnapshot(store);
// Tell React what the snapshot value is after the most recent store update.
// If it has not changed, React will not schedule any render work.
handleChange(newSnapshot);
},
);
},
[getSnapshot]
);
return useMutableSource(mutableSource, getSnapshot, subscribe);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment