Edit: forgot to add bootstrap.js
I'm trying to setup websockets using Pusher and Laravel-Echo but I'm running into a strange bug. I can see that my events are being fired on the Pusher debugger console but I'm not receiving the events on my frontend. Here is my code to setup Pusher:
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
broadcast.php
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true
],
],
app.php
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
OptionChange.php (this is my Event I'm listening for)
<?php
namespace App\Events;
use App\ItemInstance;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class OptionChange implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $instance;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(ItemInstance $instance)
{
$this->instance = $instance;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('itemInstance' . $this->instance->id);
}
// return this info in Pusher
public function broadcastWith() {
return [
'id' => $this->instance->id,
'answer' => $this->instance->answer,
'question_number' => $this->instance->question_number
];
}
}
React Code (where I'm listening for my event)
// set up channel listener for live updates
componentDidMount() {
const { started, studentId } = this.state
if (!started) {
window.Echo.channel('studentStartedTest' + studentId)
.listen('StartTest', (didStart) => {
console.log('startTest')
if (didStart) {
this.setState({ started: true })
}
})
} else {
// window.Echo.leaveChannel('studentStartedTest' + studentId)
window.Echo.channel('itemInstance' + this.props.id)
.listen('OptionChange', (instance) => {
console.log('change')
this.setState({ answer: instance.answer })
})
}
}
As you can see I'm trying a console.log whenever my event fires. Unfortunately the console.log never gets run.
I've also tried to change implements ShouldBroadcast to implements ShouldBroadcastNow but that didn't change anything