From 4b724dfa73974002019f0fc7bcdc326947775cd2 Mon Sep 17 00:00:00 2001 From: Taso Date: Fri, 23 Jul 2021 08:51:21 -0400 Subject: [PATCH] fix(phone/marketplace): fix state dispatch when selector is loading Should fix edge cases where broadcast events are received and processed before the original fetch promise resolves --- phone/src/apps/marketplace/hooks/state.ts | 2 +- .../marketplace/hooks/useMarketplaceActions.ts | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/phone/src/apps/marketplace/hooks/state.ts b/phone/src/apps/marketplace/hooks/state.ts index f45fb03..f123ef5 100644 --- a/phone/src/apps/marketplace/hooks/state.ts +++ b/phone/src/apps/marketplace/hooks/state.ts @@ -26,7 +26,7 @@ const defaultData: MarketplaceListing[] = [ }, ]; -const listingState = atom({ +export const listingState = atom({ key: 'listings', default: selector({ key: 'defaultListings', diff --git a/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts b/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts index 762c100..6e57394 100644 --- a/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts +++ b/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts @@ -1,6 +1,7 @@ import { useCallback } from 'react'; -import { useSetListings } from './state'; +import { listingState, useSetListings } from './state'; import { MarketplaceListing } from '../../../../../typings/marketplace'; +import { useRecoilValueLoadable } from 'recoil'; interface MarketplaceActionValues { deleteListing: (id: number) => void; @@ -8,20 +9,29 @@ interface MarketplaceActionValues { } export const useMarketplaceActions = (): MarketplaceActionValues => { + const { state: valueLoading, contents } = useRecoilValueLoadable(listingState); const setListings = useSetListings(); const deleteListing = useCallback( (id: number) => { + // Make sure our atom is actually loaded before we attempt a dispatch + if (valueLoading !== 'hasValue') return; + // Tts possible for the init fetch to fail and empty array is passed. In that case + // block dispatch + if (!contents.length) return; + setListings((curListings) => [...curListings].filter((listing) => listing.id !== id)); }, - [setListings], + [setListings, valueLoading, contents], ); const addListing = useCallback( (listing: MarketplaceListing) => { + // Make sure our atom is actually loaded before we attempt a dispatch + if (valueLoading !== 'hasValue') return; setListings((curListings) => [...curListings, listing]); }, - [setListings], + [setListings, valueLoading, contents], ); return { deleteListing, addListing };