Skip to content

Support "Mutations" #29

@nicoburniske

Description

@nicoburniske

Add custom mutation helpers compatible with Server actions. Rough draft below

pub fn create_server_action_with_callbacks<S>(
    on_invoke: impl Fn(&S) + 'static,
    on_settled: impl Fn((S, &Result<S::Output, ServerFnError<S::Error>>)) + 'static,
) -> Action<S, Result<S::Output, ServerFnError<S::Error>>>
where
    S: Clone + server_fn::ServerFn,
    S::Error: Clone,
{
    let on_invoke = Rc::new(on_invoke);
    let on_settled = Rc::new(on_settled);

    // The server is able to call the function directly
    #[cfg(feature = "ssr")]
    let action_function = move |args: &S| {
        let args = args.clone();
        let on_invoke = on_invoke.clone();
        let on_settled = on_settled.clone();

        async move {
            on_invoke(&args);
            let result = S::run_body(args.clone()).await;
            on_settled((args, &result));
            result
        }
    };

    // When not on the server send a fetch to request the fn call.
    #[cfg(not(feature = "ssr"))]
    let action_function = move |args: &S| {
        let args = args.clone();
        let on_invoke = on_invoke.clone();
        let on_settled = on_settled.clone();

        async move {
            on_invoke(&args);
            let result = S::run_on_client(args.clone()).await;
            on_settled((args, &result));
            result
        }
    };

    // create the action
    Action::new(action_function).using_server_fn()
}

pub fn create_server_multi_action_with_callbacks<S>(
    on_invoke: impl Fn(&S) + 'static,
    on_settled: impl Fn((S, &Result<S::Output, ServerFnError<S::Error>>)) + 'static,
) -> MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>
where
    S: Clone + server_fn::ServerFn,
{
    let on_invoke = Rc::new(on_invoke);
    let on_settled = Rc::new(on_settled);
    #[cfg(feature = "ssr")]
    let c = move |args: &S| {
        let args = args.clone();
        let on_invoke = on_invoke.clone();
        let on_settled = on_settled.clone();
        async move {
            on_invoke(&args);
            let result = S::run_body(args.clone()).await;
            on_settled((args, &result));
            result
        }
    };
    #[cfg(not(feature = "ssr"))]
    let c = move |args: &S| {
        let args = args.clone();
        let on_invoke = on_invoke.clone();
        let on_settled = on_settled.clone();
        async move {
            on_invoke(&args);
            let result = S::run_on_client(args.clone()).await;
            on_settled((args, &result));
            result
        }
    };

    create_multi_action(c).using_server_fn::<S>()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions