I have a problem that I can't resolve. I made a blog with Laravel 10, livewire 3, AlpineJS 3.
I'll show you my code.
Component livewire:
<?php
namespace App\Livewire;
use App\Models\Post;
use App\Models\Comment;
use Livewire\Component;
class CommentCreate extends Component
{
public string $content = '', $email = '', $nickname = '';
public Post $post;
public bool $creating = false;
public function mount(Post $post, bool $creating = false, $parentComment = null)
{
$this->post = $post;
$this->creating = $creating;
}
public function render()
{
return view('livewire.comment-create');
}
private function resetInputFields()
{
$this->content = '';
$this->email = '';
$this->nickname = '';
}
public function createComment()
{
$comment = Comment::create([
'content' => $this->content,
'posts_id' => $this->post->id,
'parent_id' => $this->parentComment?->id,
'email' => $this->email,
'nickname' => $this->nickname,
]);
$this->resetInputFields();
$this->dispatch('commentCreated', $comment->id);
}
}
View livewire:
<div class="mb-5">
<div x-data="{
focused: {{ $creating ? 'true' : 'false' }},
init() {
$wire.on('commentCreated'), () => {
this.focused = false;
}
}
}">
<button @click="focused = true" type="button" class="btn btn-info">
Add comment
</button>
<div class="mt-5" :class="focused ? '' : 'd-none'">
<input wire:model.live="nickname" class="form-control bg-white" type="text"
placeholder="Pseudo" aria-label="Text input with dropdown button">
<input wire:model.live="email" class="form-control bg-white mt-4"
type="email" placeholder="Email"
aria-label="Text input with dropdown button">
<textarea wire:model.live="content" class="form-control bg-white mt-4"
rows="10"
placeholder="Mettre un commentaire ici ..." aria-label="Text input with
dropdown button">
</textarea>
<div>
<button wire:click='createComment' class="btn btn-primary mt-4"
type="Submit">
<span class="text-white fw-semi-bold">Envoyer Commentaire</span>
</button>
<button @click="focused = false; isEdit = false;
$wire.dispatch('cancelEditing')" type=button
class="btn btn-info mt-4">
Cancel
</button>
</div>
</div>
</div>
</div>
In the console of the browser I have multi errors everytime I try to click on send in add post. And the form doesn't collapse because I want this everytime someone send a comment.
view of add comment and CRUD of post
I don't know what to try anymore.
Can you help me please ?
Bye
Note that you have a misplaced parenthesis, the initialization of the event listener should be:
$wire.on('commentCreated', () => {
this.focused = false;
})
Some magic properties may not be available in the init() function, you can try replacing $wire with Livewire:
Livewire.on('commentCreated', () => {
but the shortest way to listen to a (custom) event is using x-on or its short hand notation @:
<div x-data="{focused: {{ $creating ? 'true' : 'false' }}}"
@comment-created.camel.window="focused = false"
>