Skip to content

Commit

Permalink
Newswires UI: Update pagination logic
Browse files Browse the repository at this point in the history
  • Loading branch information
sb-dev committed Jan 24, 2025
1 parent 6b19f70 commit 7f1c1e0
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 86 deletions.
4 changes: 1 addition & 3 deletions newswires/client/src/Feed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ export const Feed = () => {
titleSize="s"
/>
)}
{(status == 'success' ||
status == 'offline' ||
status == 'loading-more') &&
{(status == 'success' || status == 'offline') &&
queryData.results.length > 0 && (
<WireItemTable wires={queryData.results} />
)}
Expand Down
27 changes: 18 additions & 9 deletions newswires/client/src/WireItemTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
useEuiTheme,
} from '@elastic/eui';
import { css } from '@emotion/react';
import { useState } from 'react';
import sanitizeHtml from 'sanitize-html';
import { useSearch } from './context/SearchContext.tsx';
import { formatTimestamp } from './formatTimestamp';
Expand All @@ -32,15 +33,22 @@ const fadeOutBackground = css`
`;

export const WireItemTable = ({ wires }: { wires: WireData[] }) => {
const {
config,
handleSelectItem,
state: { status },
loadMoreResults,
} = useSearch();
const { config, handleSelectItem, loadMoreResults } = useSearch();

const [isLoading, setIsLoading] = useState<boolean>(false);

const selectedWireId = config.itemId;

const handleLoadMoreResults = () => {
setIsLoading(true);

const beforeId = Math.min(...wires.map((wire) => wire.id)).toString();

void loadMoreResults(beforeId).finally(() => {
setIsLoading(false);
});
};

return (
<>
<EuiTable
Expand Down Expand Up @@ -71,13 +79,13 @@ export const WireItemTable = ({ wires }: { wires: WireData[] }) => {
</EuiTableBody>
</EuiTable>
<EuiButton
isLoading={status === 'loading-more'}
isLoading={isLoading}
css={css`
margin-top: 12px;
`}
onClick={loadMoreResults}
onClick={handleLoadMoreResults}
>
{status === 'loading-more' ? 'Loading' : 'Load more'}
{isLoading ? 'Loading' : 'Load more'}
</EuiButton>
</>
);
Expand Down Expand Up @@ -118,6 +126,7 @@ const WireDataRow = ({
background-color: ${primaryBgColor};
border-left: 4px solid ${theme.euiTheme.colors.accent};
}
border-left: 4px solid
${selected ? theme.euiTheme.colors.primary : 'transparent'};
${isFromRefresh ? fadeOutBackground : ''}
Expand Down
46 changes: 13 additions & 33 deletions newswires/client/src/context/SearchContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,6 @@ const StateSchema = z.discriminatedUnion('status', [
successfulQueryHistory: SearchHistorySchema,
autoUpdate: z.boolean().default(true),
}),
z.object({
status: z.literal('loading-more'),
error: z.string().optional(),
queryData: WiresQueryResponseSchema,
successfulQueryHistory: SearchHistorySchema,
autoUpdate: z.boolean().default(true),
}),
z.object({
status: z.literal('success'),
error: z.string().optional(),
Expand Down Expand Up @@ -79,7 +72,6 @@ export type State = z.infer<typeof StateSchema>;
// Action Schema
const ActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('ENTER_QUERY') }),
z.object({ type: z.literal('LOAD_MORE_RESULTS') }),
z.object({
type: z.literal('FETCH_SUCCESS'),
query: QuerySchema,
Expand Down Expand Up @@ -112,7 +104,7 @@ export type SearchContextShape = {
handleNextItem: () => void;
handlePreviousItem: () => void;
toggleAutoUpdate: () => void;
loadMoreResults: () => void;
loadMoreResults: (beforeId: string) => Promise<void>;
};
export const SearchContext: Context<SearchContextShape | null> =
createContext<SearchContextShape | null>(null);
Expand Down Expand Up @@ -180,29 +172,9 @@ export function SearchContextProvider({ children }: PropsWithChildren) {
});
}

if (state.status === 'loading-more') {
fetchResults(currentConfig.query, {
beforeId: Math.min(
...state.queryData.results.map((wire) => wire.id),
).toString(),
})
.then((data) => {
dispatch({ type: 'APPEND_RESULTS', data });
})
.catch((error) => {
const errorMessage =
error instanceof Error ? error.message : 'unknown error';
dispatch({ type: 'FETCH_ERROR', error: errorMessage });
});
}

if (
state.status === 'success' ||
state.status === 'offline' ||
state.status === 'loading-more'
) {
if (state.status === 'success' || state.status === 'offline') {
pollingInterval = setInterval(() => {
if (state.autoUpdate && state.status !== 'loading-more') {
if (state.autoUpdate) {
fetchResults(currentConfig.query, {
sinceId: Math.max(
...state.queryData.results.map((wire) => wire.id),
Expand Down Expand Up @@ -305,8 +277,16 @@ export function SearchContextProvider({ children }: PropsWithChildren) {
dispatch({ type: 'TOGGLE_AUTO_UPDATE' });
};

const loadMoreResults = () => {
dispatch({ type: 'LOAD_MORE_RESULTS' });
const loadMoreResults = async (beforeId: string): Promise<void> => {
return fetchResults(currentConfig.query, { beforeId })
.then((data) => {
dispatch({ type: 'APPEND_RESULTS', data });
})
.catch((error) => {
const errorMessage =
error instanceof Error ? error.message : 'unknown error';
dispatch({ type: 'FETCH_ERROR', error: errorMessage });
});
};

return (
Expand Down
20 changes: 1 addition & 19 deletions newswires/client/src/context/SearchReducer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ describe('SearchReducer', () => {
queryData: { results: [sampleWireData] },
};

const loadingMoreState: State = {
...initialState,
status: 'loading-more',
queryData: { results: [sampleWireData] },
};

const offlineState: State = {
status: 'offline',
queryData: { results: [sampleWireData] },
Expand Down Expand Up @@ -106,7 +100,7 @@ describe('SearchReducer', () => {

it(`should handle APPEND_RESULTS action in loading-more state`, () => {
const state: State = {
...loadingMoreState,
...successState,
queryData: { results: [{ ...sampleWireData, id: 2 }] },
};

Expand Down Expand Up @@ -167,16 +161,4 @@ describe('SearchReducer', () => {
expect(newState.status).toBe('loading');
});
});

[successState, offlineState].forEach((state) => {
it(`should handle LOAD_MORE_RESULTS action in ${state.status} state`, () => {
const action: Action = {
type: 'LOAD_MORE_RESULTS',
};

const newState = SearchReducer(state, action);

expect(newState.status).toBe('loading-more');
});
});
});
27 changes: 5 additions & 22 deletions newswires/client/src/context/SearchReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,11 @@ export const SearchReducer = (state: State, action: Action): State => {
return state;
}
case 'APPEND_RESULTS':
switch (state.status) {
case 'loading-more':
return {
...state,
status: 'success',
queryData: appendQueryData(state.queryData, action.data),
};
default:
return state;
}
return {
...state,
status: 'success',
queryData: appendQueryData(state.queryData, action.data),
};
case 'FETCH_ERROR':
switch (state.status) {
case 'loading':
Expand Down Expand Up @@ -142,18 +137,6 @@ export const SearchReducer = (state: State, action: Action): State => {
...state,
status: 'loading',
};
case 'LOAD_MORE_RESULTS':
switch (state.status) {
case 'success':
case 'offline':
return {
...state,
status: 'loading-more',
};
default:
return state;
}

default:
return state;
}
Expand Down

0 comments on commit 7f1c1e0

Please sign in to comment.