i am using laravel-echo to create and use websocket in my react-app. its easy to use laravel-echo in a page. but when need to use in several pages, it make several channel and subscribe several time. how to make a single channel and join ones in several pages ? with props or something ...
i try via props like below but there was some error:
parent Component:
import Echo from 'laravel-echo';
const token = window.localStorage.getItem('access_token');
const options = {
broadcaster: 'pusher',
key: '7890165486',
wsHost: '45.149.78.4',
wsPort: 6001,
disableStats: true,
authEndpoint: 'http://xxx.xxx.net/broadcasting/auth',
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
}
};
const echo = new Echo(options);
Class ParentComponnet extends Component {
componentDidMount() {
this.EchoJoin();
}
EchoJoin() {
let ch = echo.join(`chat.${this.props.token}`);
ch
.here((user) => {
console.log('all online use', user);
})
.joining((user) => {
alert(user.id + ' New Join the Channel');
})
.leaving((user) => {
alert(user.id + ' Leave the Channel');
})
.listen('MessageSent', (e) => {
console.log('>>>>>>>>>>>>', e);
});
}
<ChildComponent ch={this.echo} />
}
and this is child Component code :
componentDidMount() {
this.props.ch
.here((user) => {
console.log('all online use', user);
})
.joining((user) => {
alert(user.id + ' New Join the Channel');
})
.leaving((user) => {
alert(user.id + ' Leave the Channel');
})
.listen('MessageSent', (e) => {
console.log('>>>>>>>>>>>>', e);
});
}