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
This commit is contained in:
Taso committed 2021-07-27 17:06:52 -04:00
1 parent 44599c882d
commit 4b724dfa73
2 files changed
+14 -4

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ const defaultData: MarketplaceListing[] = [
},
];
const listingState = atom<MarketplaceListing[]>({
export const listingState = atom<MarketplaceListing[]>({
key: 'listings',
default: selector({
key: 'defaultListings',
@@ -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 };