symfony / ux

Symfony UX initiative: a JavaScript ecosystem for Symfony
https://ux.symfony.com/
MIT License
851 stars 313 forks source link

[LiveComponent] Force POST method when model is changed #1208

Closed hepisec closed 9 months ago

hepisec commented 1 year ago

Hello,

I've built my first LiveComponent and it works well. But I've noticed that backend requests are sent as GET with all props being appended as URL parameters. As my component includes sensitive data, I want to change the request method to POST. According to the code this could be achieved by adding an action (see https://github.com/symfony/ux/blob/d3ce11f105579c95cab72d5967ff7875c9e3da6b/src/LiveComponent/assets/src/Backend/RequestBuilder.ts#L38). But when I tried to add an data-action="live#update" attribute to my form element, I got the following error:

Error: Since LiveComponents 2.3, you no longer need data-action="live#update" on form elements. Found on element: <select data-model="mySelect" data-action="live#update">

What's the correct way to force POST for backend requests?

    <select data-model="mySelect">
        <!-- options...  should be sent as POST requests on change -->
    </select>
hepisec commented 1 year ago

I got a working solution:

Within my component class:

    /**
     * this action is used to force POST requests
     */
    #[LiveAction]
    public function update(): void
    {        
    }

And my form element:

<select data-model="mySelect" data-action="live#action" data-action-name="update">
</select>

Let me know if there is a better way, thx.

weaverryan commented 1 year ago

Clever solution :). You're the first person to ask about this. We could add an option on AsLiveClomponent for this - e.g. AsLiveComponent(forcePost: true).

hepisec commented 1 year ago

I could try to implement this.

But I'm curious, what is the reason to send the requests using GET by default?

weaverryan commented 1 year ago

But I'm curious, what is the reason to send the requests using GET by default?

Theoretical HTTP caching :). And also, it just seems more correct - you have a repeatable URL that you can use to render in different states.