techdocs: memoize useReaderState result

Signed-off-by: Vincenzo Scamporlino <vincenzos@spotify.com>
This commit is contained in:
Vincenzo Scamporlino
2024-11-12 13:35:08 +01:00
parent 3cc013d2e4
commit f73b5e4785
2 changed files with 58 additions and 9 deletions
@@ -687,5 +687,43 @@ describe('useReaderState', () => {
expect.any(Function),
);
});
it('should return the same data if re-rendered', async () => {
techdocsStorageApi.getEntityDocs.mockResolvedValue('my content');
techdocsStorageApi.syncEntityDocs.mockImplementation(async () => {
return 'cached';
});
const { result, rerender } = renderHook(
() => useReaderState('Component', 'default', 'backstage', '/example'),
{ wrapper: Wrapper },
);
expect(result.current).toEqual({
state: 'CHECKING',
path: '/example',
content: undefined,
contentErrorMessage: undefined,
syncErrorMessage: undefined,
buildLog: [],
contentReload: expect.any(Function),
});
await waitFor(() => {
expect(result.current).toEqual({
state: 'CONTENT_FRESH',
path: '/example',
content: 'my content',
contentErrorMessage: undefined,
syncErrorMessage: undefined,
buildLog: [],
contentReload: expect.any(Function),
});
});
const firstResult = result.current;
rerender();
expect(result.current).toBe(firstResult);
});
});
});
@@ -343,13 +343,24 @@ export function useReaderState(
[state.activeSyncState, state.content, state.contentLoading],
);
return {
state: displayState,
contentReload,
path: state.path,
content: state.content,
contentErrorMessage: state.contentError?.toString(),
syncErrorMessage: state.syncError?.toString(),
buildLog: state.buildLog,
};
return useMemo(
() => ({
state: displayState,
contentReload,
path: state.path,
content: state.content,
contentErrorMessage: state.contentError?.toString(),
syncErrorMessage: state.syncError?.toString(),
buildLog: state.buildLog,
}),
[
displayState,
contentReload,
state.path,
state.content,
state.contentError,
state.syncError,
state.buildLog,
],
);
}