Implement Optimistic Effects (#1415)
* Fix person deletion not reflected on Opportunities POC * Fix companies, user deletion * Implement optimistic effects * Implement optimistic effects * Implement optimistic effects * Fix accoding to PR
This commit is contained in:
@ -0,0 +1,48 @@
|
||||
import { useApolloClient } from '@apollo/client';
|
||||
import { useRecoilCallback } from 'recoil';
|
||||
|
||||
import { optimisticEffectState } from '../states/optimisticEffectState';
|
||||
import { OptimisticEffect } from '../types/OptimisticEffect';
|
||||
|
||||
export function useOptimisticEffect() {
|
||||
const apolloClient = useApolloClient();
|
||||
|
||||
const registerOptimisticEffect = useRecoilCallback(
|
||||
({ snapshot, set }) =>
|
||||
(optimisticEffect: OptimisticEffect<unknown, unknown>) => {
|
||||
const { key } = optimisticEffect;
|
||||
const optimisticEffects = snapshot
|
||||
.getLoadable(optimisticEffectState)
|
||||
.getValue();
|
||||
|
||||
set(optimisticEffectState, {
|
||||
...optimisticEffects,
|
||||
[key]: optimisticEffect,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const triggerOptimisticEffects = useRecoilCallback(
|
||||
({ snapshot }) =>
|
||||
(typename: string, entities: any[]) => {
|
||||
const optimisticEffects = snapshot
|
||||
.getLoadable(optimisticEffectState)
|
||||
.getValue();
|
||||
|
||||
Object.values(optimisticEffects).forEach((optimisticEffect) => {
|
||||
if (optimisticEffect.typename === typename) {
|
||||
optimisticEffect.resolver({
|
||||
cache: apolloClient.cache,
|
||||
entities,
|
||||
variables: optimisticEffect.variables,
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
registerOptimisticEffect,
|
||||
triggerOptimisticEffects,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
import { atom } from 'recoil';
|
||||
|
||||
import { OptimisticEffect } from '../types/OptimisticEffect';
|
||||
|
||||
export const optimisticEffectState = atom<
|
||||
Record<string, OptimisticEffect<unknown, unknown>>
|
||||
>({
|
||||
key: 'optimisticEffectState',
|
||||
default: {},
|
||||
});
|
||||
@ -0,0 +1,18 @@
|
||||
import { ApolloCache } from '@apollo/client';
|
||||
|
||||
type OptimisticEffectResolver<T, QueryVariables> = ({
|
||||
cache,
|
||||
entities,
|
||||
variables,
|
||||
}: {
|
||||
cache: ApolloCache<T>;
|
||||
entities: T[];
|
||||
variables: QueryVariables;
|
||||
}) => void;
|
||||
|
||||
export type OptimisticEffect<T, QueryVariables> = {
|
||||
key: string;
|
||||
typename: string;
|
||||
variables: QueryVariables;
|
||||
resolver: OptimisticEffectResolver<T, QueryVariables>;
|
||||
};
|
||||
Reference in New Issue
Block a user