i take care of frontend part using ReactJS of a Laravel project. Currently i implement the notifications with using Laravel Echo Server. I render and update State well but the problem is every time there's a new notification, my component does not recognize it. Here is my Notifications component:
import React, {Component} from 'react';
import Echo from "laravel-echo";
class Notifications extends Component {
constructor(props) {
super(props);
this.state = {
userLogin: {}
};
}
componentDidMount(){
axios.post(laroute.route('api.get-users'))
.then(res=>{
this.setState({
userLogin:res.data.userLogin
});
})
.catch(err=>{
console.log(err);
})
window.Echo.private('users.' + this.state.userLogin.id)
.notification((notification) => {
console.log(notification);
});
}
render() {
return (
<span>
Notifications
</span>
)
}
}
export default Notifications;
I tried to change ComponentDidMount to ConmponentWillMount but it still not working for the notification. Funny thing is that if i put those Listening For Notifications inside blade template, it works well:
@section('header')
....
@endsection
@section('after-scripts')
<script>
var userId= "{{ access()->user()->id }}";
window.Echo.private('users.' + userId)
.notification((notification) => {
console.log(notification);
});
</script>
@endsection
axios.post
would result in a value asynchronously. But your window.Echo.private
would run before that. Move it inside and check if it works.
Here, give this a try:
componentDidMount() {
axios.post(laroute.route('api.get-users'))
.then(res => {
const { userLogin } = res.data;
window.Echo.private('users.' + userLogin.id)
.notification(notification => console.log(notification));
this.setState({
userLogin
});
})
.catch(err => console.log(err))
}