Best practices for inter-component data passing using events

I have a use case where I have some data (let’s say a burger menu) and I have a filters component (let’s say filter by ingredient) that should be used to filter through the data. How should one go about building this using Livewire?

Here’s what I’ve come up with: the filters component internally keeps a json representation of the filters (eg. a list of the ids of the ingredients that have been selected). When the filters change, the filters component emits a filtersChanged event. Other components (eg. the menu) listen for this event and when received, take the json representation of the filters and re-compute the items that match.

I have a bit of an issue with this approach:
How does one avoid the potential issue of the event payload format changing by the emitter without necessarily using tests?

Any ideas are welcome!

I understand what you are trying to do, but not your question itself fully. I personally don’t see a problem with your approach (you might be making extra work for yourself using json objects if the data is only being used by livewire, but you could be using it elsewhere too). I could be wrong, I’m reading this as you are worried about the different components becoming out of sync with each other?

Hi @xxdalexx. Yeah pretty much. Maybe I’m being a bit paranoid. Testing components should cover this issue… I guess what I was really asking is if there’s a more vuex-y approach to state management across livewire components (other than events).

I use a healthy amount of events, and I haven’t run into any problems passing data publicly, but I tend to keep more things server side using sessions and caching. My reasoning is a little different, and more for security, but the same concept could be applied here. Sessions if it’s user specific, cache if it should reach all users, so for filters I’m assuming you would use sessions.

The basic workflow would be

  • Your filters component would save the data to the session.
  • Fire an event to your other components.
  • Those components read the data from the session when they receive the event and do whatever.

That could alleviate your concerns because that would put your data in a centralized place for one component to write to and the others to read from, instead of each component having a copy of their own. I can go into more detail with code examples if you need.

3 Likes

I really didn’t think of that. Sounds like a cool approach that would make me happier :grinning:
I’ll go ahead and try this and comment back with my conclusions. Thanks Dale!