Improved short URL detail redux action so that it avoids API calls when the URL is found in local state

This commit is contained in:
Alejandro Celaya
2021-03-05 16:25:20 +01:00
parent 56b3523c5b
commit 13d3a95a06
2 changed files with 47 additions and 9 deletions

View File

@@ -4,6 +4,7 @@ import { buildReducer } from '../../utils/helpers/redux';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { OptionalString } from '../../utils/utils';
import { GetState } from '../../container/types';
import { shortUrlMatches } from '../helpers';
/* eslint-disable padding-line-between-statements */
export const GET_SHORT_URL_DETAIL_START = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL_START';
@@ -37,10 +38,12 @@ export const getShortUrlDetail = (buildShlinkApiClient: ShlinkApiClientBuilder)
domain: OptionalString,
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: GET_SHORT_URL_DETAIL_START });
const { getShortUrl } = buildShlinkApiClient(getState);
try {
const shortUrl = await getShortUrl(shortCode, domain);
const { shortUrlsList } = getState();
const shortUrl = shortUrlsList?.shortUrls?.data.find(
(shortUrl) => shortUrlMatches(shortUrl, shortCode, domain),
) ?? await buildShlinkApiClient(getState).getShortUrl(shortCode, domain);
dispatch<ShortUrlDetailAction>({ shortUrl, type: GET_SHORT_URL_DETAIL });
} catch (e) {