Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created January 1, 2019 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/f70671d56c098e6a53a3398ff1779b18 to your computer and use it in GitHub Desktop.
Save Noitidart/f70671d56c098e6a53a3398ff1779b18 to your computer and use it in GitHub Desktop.
import React from 'react'
class NotificationMenuBarItem extends React.Component {
state = {
notifs: []
}
componentDidMount() {
this.setupConnections();
}
render() {
return (
<React.Fragment>
<a className="nav-item nav-link ml-2 ml-md-0 mr-2">
<i className="fa fa-bell-o"></i>
</a>
<a className="nav-item nav-link ml-2 ml-md-0 mr-2" onClick={this.createFakeNotifs}>
New Fake Notif
</a>
</React.Fragment>
);
}
async setupConnections() {
await Promise.all([
this.fetchUnreadNotifs(),
this.watchNotifs()
]);
console.log('ok watching');
}
async fetchUnreadNotifs() {
const res = await fetch('/notification');
console.log('res:', res);
if (res.status === 200) {
const reply = await res.json();
console.log('reply:', reply);
} // TODO: handle error
}
watchNotifs() {
// subscribe to notification chanel - MUST have prefix slash
new Promise(resolve => {
// watch new things, will not work unless subscribed first - MUST NOT HAVE prefix slash
io.socket.on('notification', function(msg, ...args) {
console.log('socket ON msg:', msg, ...args);
});
// subscript to it so .on('notification') works
new Promise(resolve => io.socket.get('/notification', resolve));
});
}
async createFakeNotifs() {
const res = await fetch('/notification', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': SAILS_LOCALS._csrf
},
body: JSON.stringify({
user: SAILS_LOCALS.me.id,
type: 'ResidentCreatedMessage',
dataVersion: 0,
data: JSON.stringify({
body: 'lorem ipsum',
authorName: 'foo name'
})
})
});
console.log('create res:', res);
if (res.status >= 400) {
console.log('failed text:', await res.text());
} else {}
}
}
export default NotificationMenuBarItem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment