0

I’m fairly new to the components & livewire game so I’m getting very confusing when I need to update a component value from other sources. Let me explain:

I’m using a default Laravel 8 installation with Livewire - no JetStream.

My navigation file (the default one that comes with the installation) has 3 individual components containing: total of points achieved, total of lives and remaining lives.

Loads like:

<x-points>0</x-points>

<x-lifes>0</x-lifes>

<x-remaining-lifes>0</x-remainung-lifes>

My question: how do I update any of those components when I execute actions from different sources like:

  • user answer a question (file Answer.php)
  • User clicks on an action at the footer of my application (let’s call this Regenerate.php)
  • User request tips so I need to subtract (Tips.php)

1 Answer 1

1

I would change your three main blade components for livewire componentes:

<livewire:points></livewire:points>

<livewire:lifes></livewire:lifes>

<livewire:remaining-lifes></livewire:remaining-lifes>

So for example, let's create the points and answer components.

// Points.php livewire component

public int points = 0;

public $listeners = ['loadUserPoints'];

public function render() { ... }

public function loadUserPoints()
{
     $this->points = user()->points()->sum('total');
}
// points.blade.php livewire component

<div wire:init="loadUserPoints">{{ $points }}</div>

Now let's abstract the answer component.

// answer livewire component (very abstracted)

public function save()
{
     user()->answers()->create($this->data);

     // this will be listened by the points component
     // that will run its query and update your frontend
     $this->emit('loadUserPoints');
}

So livewire works mainly for events, you have to use it to pass data cross multiple components. To update your frontend as an SPA you're not gonna use blade components, you have to use livewire component or a lot of javascript to handle the DOM.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That's kinda what I did. I've been asking myself when to use <livewire:points></livewire:points> vs <x-points />?
In my projects the laravel blade components that I use is most for static behavior, like inputs, dropdowns, this kind of stuff. I use livewire when the user expects a SPA behavior like a ecommerce cart, some filter/search on the page, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.