Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow default values for absent server_fn argument deserialization #1745

Closed
wants to merge 1 commit into from

Conversation

g2p
Copy link
Contributor

@g2p g2p commented Sep 17, 2023

This allows form submission with checkbox inputs to work.
For example:

let doit = create_server_action::<DoItSFn>();
<ActionForm action=doit>
  <input type="checkbox" name="is_good" value="true"/>
  <input type="submit"/>
</ActionForm>

#[server(DoItSFn, "/api")]
pub async fn doit(is_good: bool) -> Result<(), ServerFnError> {}

Arguments absent in the request to the server API will use the Default::default() constructor.

Discussion

Maybe this could be restricted to only certain types; at the moment bool and String need it (for checkboxes and radio buttons) and I don't see a way to customize the (de)serialisation.
Another attempted workaround was to add
<input type"hidden" name="is_good" value="false"/>
immediately before the checkbox; serde refuses to deserialize a field that appears twice but that could probably be tweaked as well.

This allows form submission with checkbox inputs to work.
For example:

    let doit = create_server_action::<DoItSFn>();
    <ActionForm action=doit>
      <input type="checkbox" name="is_good" value="true"/>
      <input type="submit"/>
    </ActionForm>

    #[server(DoItSFn, "/api")]
    pub async fn doit(is_good: bool) -> Result<(), ServerFnError> {}

Arguments absent in the request to the server API will use the Default::default() constructor.
@g2p g2p changed the title Allow default values for absent server_fn arguments Allow default values for absent server_fn argument deserialization Sep 17, 2023
@gbj
Copy link
Collaborator

gbj commented Sep 19, 2023

I would assume that adding a blanket #[serde(default)] like this breaks every type that doesn't implement Default — is that incorrect?

A better approach might be to add an attribute to arguments that could be passed through to serde, in the same way that the #[component] macro's #[prop(optional)] passes an attribute through to typed-builder.

@g2p
Copy link
Contributor Author

g2p commented Sep 20, 2023

Good points, it was a little more involved but I have #1762 which does this for server function arguments carrying a #[server(default)] annotation.

@gbj gbj closed this Sep 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants