Skip to content

Instantly share code, notes, and snippets.

@kgoggin
Created October 20, 2022 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgoggin/b2438d3fe676d27f9cb1b85f981a143f to your computer and use it in GitHub Desktop.
Save kgoggin/b2438d3fe676d27f9cb1b85f981a143f to your computer and use it in GitHub Desktop.
Capture Fixture Data
import { useCallback } from 'react';
import { isEqual } from 'lodash';
interface UseCaptureFixtureDataConfig {
localStorageKey: string;
equalityCheck?: typeof isEqual;
}
const cache = new Map<string, unknown[]>();
/**
This hook is a pretty painless way to capture some data that you might want to use for test fixtures, or some
other purpose. To use it, drop it in a component/other hook like this:
const captureResult = useCaptureFixtureData({
localStorageKey: `useOmniEvents-fixtures-${ticketId}`,
});
Then, call `captureResult` with whatever you want to capture. The hook will try to dedupe responses so you're
left with unique entries, and write it to localStorage. From there you can copy the value out into a file or
wherever you need it.
*/
export const useCaptureFixtureData = (
config: UseCaptureFixtureDataConfig
): ((result: unknown) => void) => {
const equalityCheck = config.equalityCheck || isEqual;
const captureResult = useCallback(
(result: unknown) => {
const existing = cache.get(config.localStorageKey) || [];
const resultExists = existing.reduce((prev, prevResult) => {
if (prev) {
return true;
}
return equalityCheck(prevResult, result);
}, false);
if (resultExists) {
return;
}
const newResult = [...existing, result];
cache.set(config.localStorageKey, newResult);
window.localStorage.setItem(config.localStorageKey, JSON.stringify(newResult));
},
[config, equalityCheck]
);
return captureResult;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment