Replies: 5 comments 15 replies
-
Would something like this proposal solve this issue without leaking the promise? I think it could be applied to |
Beta Was this translation helpful? Give feedback.
-
This got discussed in Roadmap #5, around 31'50 The current idiomatic way to do this today is: let actionData = useActionData();
useEffect(() => {
if (actionData.ok) {
complete(actionData)
}
}, [actionData]); We may want to revisit returning promises from |
Beta Was this translation helpful? Give feedback.
-
Someone also mentioned wanting a promise returned from |
Beta Was this translation helpful? Give feedback.
-
Here's a simple function useSubmitPromise() {
const submit = useSubmit();
const navigation = useNavigation();
const actionData = useActionData();
const $deferred = useMemo(() => deferred(), []);
useEffect(() => {
if (navigation.state === "idle" && actionData) {
$deferred.resolve(actionData);
}
}, [$deferred, navigation.state, actionData]);
const _submit = useCallback(
(target: SubmitTarget, options: SubmitOptions = {}) => {
submit(target, options);
return $deferred.promise;
},
[$deferred.promise, submit]
);
return _submit;
}
// create a *deferred* promise
function deferred() {
let resolve: any;
let reject: any;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { resolve, reject, promise };
} And sample usage: const submit = useSubmitPromise();
const doSubmit = useCallback(
(e: any) => {
console.log("doSubmit");
e.preventDefault();
submit({ test: "123" }, { method: "post" }).then(
(data) => {
console.log(data);
}
);
},
[submit]
); |
Beta Was this translation helpful? Give feedback.
-
same for |
Beta Was this translation helpful? Give feedback.
-
I would like to be able to submit an action from inside an event handler and call a function after the submit has finished. At the moment, my implementation looks something like this
completeFn
could alternatively be stored in a ref instead, but the rest of the code remains largely the same.If
submit
returned a promise that resolved once the request had completed, it could look something like this insteadI have considered some alternatives, such as using
fetch
to call the action directly, but decided against it as it would essentially mean opting out of Remix's transition management, which is one of the big reasons I'm using Remix in the first place.A similar discussion already exists here #3955 but it wasn't actually raised as a proposal which is why I decided to start this one separately.
Beta Was this translation helpful? Give feedback.
All reactions