fix(search): when reset page cursor

Signed-off-by: Camila Belo <camilaibs@gmail.com>
This commit is contained in:
Camila Belo
2022-06-30 21:22:21 +02:00
parent 06b6920a2c
commit 7d2f89a1bd
2 changed files with 49 additions and 30 deletions
@@ -108,40 +108,58 @@ describe('SearchContext', () => {
expect(result.current).toEqual(expect.objectContaining(initialState));
});
it('Resets cursor when term is set (and different from previous)', async () => {
const { result, waitForNextUpdate } = renderHook(() => useSearch(), {
wrapper,
initialProps: {
initialState: {
...initialState,
pageCursor: 'SOMEPAGE',
describe('Resets cursor', () => {
it('When term is cleared', async () => {
const { result, waitForNextUpdate } = renderHook(() => useSearch(), {
wrapper,
initialProps: {
initialState: {
...initialState,
term: 'first term',
pageCursor: 'SOMEPAGE',
},
},
},
});
await waitForNextUpdate();
expect(result.current.term).toEqual('first term');
expect(result.current.pageCursor).toEqual('SOMEPAGE');
act(() => {
result.current.setTerm('');
});
await waitForNextUpdate();
expect(result.current.pageCursor).toBeUndefined();
});
await waitForNextUpdate();
it('When term is set (and different from previous)', async () => {
const { result, waitForNextUpdate } = renderHook(() => useSearch(), {
wrapper,
initialProps: {
initialState: {
...initialState,
term: 'first term',
pageCursor: 'SOMEPAGE',
},
},
});
expect(result.current.pageCursor).toEqual('SOMEPAGE');
await waitForNextUpdate();
act(() => {
result.current.setTerm('first term');
expect(result.current.term).toEqual('first term');
expect(result.current.pageCursor).toEqual('SOMEPAGE');
act(() => {
result.current.setTerm('second term');
});
await waitForNextUpdate();
expect(result.current.pageCursor).toBeUndefined();
});
act(() => {
result.current.setPageCursor('OTHERPAGE');
});
await waitForNextUpdate();
expect(result.current.pageCursor).toEqual('OTHERPAGE');
act(() => {
result.current.setTerm('second term');
});
await waitForNextUpdate();
expect(result.current.pageCursor).toEqual(undefined);
});
describe('Performs search (and sets results)', () => {
@@ -150,10 +150,11 @@ export const SearchContextProvider = (props: SearchContextProviderProps) => {
useEffect(() => {
// Any time a term is reset, we want to start from page 0.
if (term && prevTerm && term !== prevTerm) {
// Only reset the term if it has been modified by the user at least once, the initial state must not reset the term.
if (prevTerm !== undefined && term !== prevTerm) {
setPageCursor(undefined);
}
}, [term, prevTerm, initialState.pageCursor]);
}, [term, prevTerm, setPageCursor]);
const value: SearchContextValue = {
result,