fix: add optimistic update for disabling forms (#5547)

pr/5569
Nafees Nazik 2022-12-08 02:25:41 +05:30 committed by GitHub
parent 4686d3ff48
commit 4e02b22472
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 22 additions and 5 deletions

View File

@ -234,14 +234,31 @@ const actionsCtx = createContext({
export function FormActionsProvider({ appUrl, children }: { appUrl: string; children: React.ReactNode }) {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteDialogFormId, setDeleteDialogFormId] = useState<string | null>(null);
const router = useRouter();
const utils = trpc.useContext();
const toggleMutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onError: () => {
showToast(`Something went wrong`, "error");
onMutate: async ({ id: formId, disabled }) => {
await utils.viewer.appRoutingForms.forms.cancel();
const previousValue = utils.viewer.appRoutingForms.forms.getData();
if (previousValue) {
const itemIndex = previousValue.findIndex(({ id }) => id === formId);
const prevValueTemp = [...previousValue];
if (itemIndex !== -1 && prevValueTemp[itemIndex] && disabled !== undefined) {
prevValueTemp[itemIndex].disabled = disabled;
}
utils.viewer.appRoutingForms.forms.setData(undefined, prevValueTemp);
}
return { previousValue };
},
onSuccess: () => {
router.replace(router.asPath);
onSettled: () => {
utils.viewer.appRoutingForms.forms.invalidate();
},
onError: (err, value, context) => {
if (context?.previousValue) {
utils.viewer.appRoutingForms.forms.setData(undefined, context.previousValue);
}
showToast("Something went wrong", "error");
},
});