fix: add optimistic update for disabling forms (#5547)
parent
4686d3ff48
commit
4e02b22472
|
@ -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");
|
||||
},
|
||||
});
|
||||
|
||||
|
|
Loading…
Reference in New Issue