symfony / ux

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

[LiveComponent] Re-initialize upon visibility #1847

Open gerritwitkamp opened 3 months ago

gerritwitkamp commented 3 months ago

Hi,

Right now we're using a lazy Live Component in a modal, which gets initialized when the modal becomes visible; that's working great. I was wondering if it's possible to 're-initialize' a Live Component when become visible again, so not only the first time. I only managed by adding a custom Stimulus controller that communicates with the Live Component by calling a 'init'-method. Thanks in advance.

WebMamba commented 3 months ago

I don't think we want it in the core but this is a great think you can still share your code here! 😁

gerritwitkamp commented 3 months ago

@WebMamba Well, I think it's a great addition. Imagine the following use case: I have an overview with entities and in that overview I have an add-button which opens a modal with that Live Component. I do want to reset the underlying form everytime the modal get's openend. Right now, with lazy, it's only 'reset' upon first init.

smnandre commented 3 months ago

You can look how i did it for the icon modals on this page: https://ux.symfony.com/icons (source code is in the repository)

I agree with you this is a frequent pattern, but ... the implementation is really different from a project to another.. so maybe we should write a short post in the cookbook ?

gerritwitkamp commented 3 months ago

@smnandre Thanks, I will have look. Adding it to the cookbook would be great.

gerritwitkamp commented 3 months ago

@smnandre just checked the repo, your implementation is slightly different from mine. Your trigger is the Click + Change event. I have added a create and edit (with livearg id) method in the live component, which is called from the records in the overview. When editing, the entity is fetched and populates the form. When creating, resetForm is called. The modal is shown using dispatchBrowserEvent.

gerritwitkamp commented 3 months ago

@smnandre I end up using a single turbo-frame in my base-template. Using a Stimulus-controller I can change the src-attribute, the route returns a complete modal-HTML. With the frame-events I can show a backdrop + loader during fetching. When fetch completes the Stimulus controller creates a Bootstrap modal. Turbo doesn't intercept Live Component, so far it's looking good. Because the turbo-frame refetched the src again and again, it's the same 'effect' as re-initialize.