1

I am dispatching an event from my Livewire Component when a button is clicked to pass data to another Component.

public function updateSongs(int $index)
{
    $this->dispatchBrowserEvent('audio:updated', ['songs' => $this->albums[$index -1]['songs']]);
}

My other component listens for this event like so

window.addEventListener('audio:updated', event => {
   const songs = event.detail.songs; // console.log shows expected data
   Livewire.emit('songsUpdated', songs);
});

I then have a listener, which attaches to a function that updates the songs to the new songs:

class AudioPlayer extends Component
{
    public array $songs = [];
    protected $listeners = ['songsUpdated' => 'updateSongs'];

    protected function getListeners(): array
    {
        return ['songsUpdated' => 'updateSongs'];
    }

    public function render()
    {
        return view('livewire.audio-player', [
            'songs' => $this->songs,
        ]);
    }

    public function updateSongs(array $json)
    {
        $this->songs = $json;
    }
}

When the AudioPlayer is first rendered:

@livewire('audio-player', ['songs' => [
    [
        'id' => 1,
         'name' => '4x4',
         'artist' => 'Young T ft Bugsey',
         'cover' => 'https://i1.sndcdn.com/artworks-000237133916-4rd8mi-t500x500.jpg',
         'duration' => '3:42',
    ],
]])

It loads the data perfectly fine. However, when the listener executes the function via emit with the new given songs and updates the $this->songs - the page does not change and the component does not refresh with the new data.

I did a var_dump($json) which gives me my expected result when I check the network tab. Can anyone lend a hand on what I'm missing here?

Jaquarh
  • 6,493
  • 7
  • 34
  • 86

1 Answers1

0

Try to re-render

public function updateSongs(array $json)
{
    $this->songs = $json;
    $this->render();
}
Digvijay
  • 7,836
  • 3
  • 32
  • 53
  • Sorry, failed to mention that I tried this. I also then tried to `return $this->render();` which did not work either. I found that Livewire expects the component to be inside one `
    ` where as my actual component contained multiple which is why it wasn't rendering. I will mark as duplicate to which question solved my issue.
    – Jaquarh Feb 08 '21 at 14:22