0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-18 18:42:41 +00:00

"Refactor notification utils components to use React Hooks instead of createClass"

This commit is contained in:
Víctor Losada Hernández
2024-08-29 00:01:02 +02:00
parent 46882c4fb4
commit 51d3d11bff
3 changed files with 184 additions and 172 deletions

View File

@@ -1,101 +1,113 @@
require('./notificationAdd.less'); require('./notificationAdd.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const { useState } = require('react');
const cx = require('classnames'); const cx = require('classnames');
const request = require('superagent'); const request = require('superagent');
const fields = ['dismissKey', 'title', 'text', 'startAt', 'stopAt']; const fields = ['dismissKey', 'title', 'text', 'startAt', 'stopAt'];
const NotificationAdd = () => {
const NotificationAdd = createClass({ const [state, setState] = useState({
displayName : 'NotificationAdd',
getDefaultProps() {
return {};
},
getInitialState() {
return {
query: '', query: '',
notificationResult: null, notificationResult: null,
searching: false, searching: false,
error: null, error: null,
dismissKey: '',
title: '',
text: '',
startAt: '',
stopAt: ''
});
const handleChange = (e, field) => {
const value = e.target.value;
setState(prevState => ({
...prevState,
[field]: value
}));
};
const saveNotification = async () => {
if (!state.dismissKey) {
setState(prevState => ({
...prevState,
error: 'No notification key!'
}));
return;
}
const data = {
dismissKey: state.dismissKey,
title: state.title,
text: state.text,
startAt: Date.parse(state.startAt),
stopAt: Date.parse(state.stopAt)
};
try {
const response = await request.post('/admin/notification/add').send(data);
const notification = response.body;
let update = {
notificationResult: `Created notification: ${JSON.stringify(notification, null, 2)}`
};
if (notification.err) {
update.notificationResult = JSON.stringify(notification.err);
if (notification.err.code == 11000) {
update.notificationResult = `Duplicate dismissKey error! ${state.dismissKey} already exists.`;
}
} else {
update = {
...update,
dismissKey: '', dismissKey: '',
title: '', title: '',
text: '', text: '',
startAt: '', startAt: '',
stopAt: '' stopAt: ''
}; };
},
handleChange(e, field){
const data = {};
data[field] = e.target.value;
this.setState(data);
},
saveNotification : async function(){
if(!this.state.dismissKey) return 'No notification key!';
const data = {
dismissKey : this.state.dismissKey,
title : this.state.title,
text : this.state.text,
startAt : Date.parse(this.state.startAt),
stopAt : Date.parse(this.state.stopAt)
};
const notification = await request.post('/admin/notification/add')
.send(data)
.then((response)=>{
return response.body;
});
const update = {
notificationResult : `Created notification: ${JSON.stringify(notification, null, 2)}`
};
if(notification.err) {
update.notificationResult = JSON.stringify(notification.err);
if(notification.err.code == 11000) {
update.notificationResult = `Duplicate dismissKey error! ${this.state.dismissKey} already exists.`;
}
};
if(!notification.err) {
update.dismissKey = '';
update.title = '';
update.text = '';
update.startAt = '';
update.stopAt = '';
} }
console.log(update); setState(prevState => ({
...prevState,
...update,
searching: false
}));
} catch (err) {
setState(prevState => ({
...prevState,
error: err.message,
searching: false
}));
}
};
this.setState(update); return (
}, <div className='notificationAdd'>
render(){
return <div className='notificationAdd'>
<h2>Add</h2> <h2>Add</h2>
{fields.map((field, idx)=>{ {fields.map((field, idx) => (
return <div key={idx}> <div key={idx}>
<label className='fieldLabel'>{field.toUpperCase()}</label> <label className='fieldLabel'>{field.toUpperCase()}</label>
<input className='fieldInput' type='text' value={this.state[field]} onChange={(e)=>this.handleChange(e, field)} placeholder={field} /> <input
</div>; className='fieldInput'
type='text'
value={state[field]}
onChange={(e) => handleChange(e, field)}
placeholder={field}
/>
</div>
))}
<div className='notificationResult'>{state.notificationResult}</div>
<button onClick={saveNotification}>
<i
className={cx('fas', {
'fa-save': !state.searching,
'fa-spin fa-spinner': state.searching
})} })}
<div className='notificationResult'>{this.state.notificationResult}</div> />
{/* <label>Dismiss Key:</label>
<input type='text' value={this.state.dismissKey} onChange={this.handleChange} placeholder='notification key' />
<label>Title:</label>
<input type='text' value={this.state.title} onChange={this.handleChange} placeholder='title' /> */}
<button onClick={this.saveNotification}>
<i className={cx('fas', {
'fa-save' : !this.state.searching,
'fa-spin fa-spinner' : this.state.searching,
})} />
</button> </button>
{state.error && <div className='error'>{state.error.toString()}</div>}
{this.state.error </div>
&& <div className='error'>{this.state.error.toString()}</div> );
} };
</div>;
}
});
module.exports = NotificationAdd; module.exports = NotificationAdd;

View File

@@ -1,94 +1,97 @@
require('./notificationLookup.less'); require('./notificationLookup.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const { useState } = require('react');
const cx = require('classnames'); const cx = require('classnames');
const request = require('superagent'); const request = require('superagent');
const Moment = require('moment'); const Moment = require('moment');
const NotificationLookup = () => {
const [query, setQuery] = useState('');
const [foundNotification, setFoundNotification] = useState(null);
const [searching, setSearching] = useState(false);
const [error, setError] = useState(null);
const NotificationLookup = createClass({ const handleChange = (e) => {
displayName : 'NotificationLookup', setQuery(e.target.value);
getDefaultProps() {
return {};
},
getInitialState() {
return {
query : '',
foundNotification : null,
searching : false,
error : null
}; };
},
handleChange(e){
this.setState({ query: e.target.value });
},
lookup(){
this.setState({ searching: true, error: null });
request.get(`/admin/notification/lookup/${this.state.query}`) const lookup = () => {
.then((res)=>this.setState({ foundNotification: res.body })) setSearching(true);
.catch((err)=>this.setState({ error: err })) setError(null);
.finally(()=>this.setState({ searching: false }));
},
deleteNotification : function(){ request.get(`/admin/notification/lookup/${query}`)
console.log('DELETE'); .then((res) => setFoundNotification(res.body))
if(!confirm(`Really delete notification ${this.state.foundNotification.dismissKey} : ${this.state.foundNotification.title}?`)) { .catch((err) => setError(err))
.finally(() => setSearching(false));
};
const deleteNotification = () => {
if (!foundNotification) return;
const confirmed = window.confirm(`Really delete notification ${foundNotification.dismissKey} : ${foundNotification.title}?`);
if (!confirmed) {
console.log('CANCELLED'); console.log('CANCELLED');
return; return;
} }
console.log('CONFIRMED'); console.log('CONFIRMED');
return; // Perform delete operation here
}, };
renderFoundNotification(){ const renderFoundNotification = () => {
const notification = this.state.foundNotification; if (!foundNotification) return null;
return <div className='foundNotification'>
return (
<div className='foundNotification'>
<dl> <dl>
<dt>Key</dt> <dt>Key</dt>
<dd>{notification.dismissKey}</dd> <dd>{foundNotification.dismissKey}</dd>
<dt>Title</dt> <dt>Title</dt>
<dd>{notification.title || 'No Title'}</dd> <dd>{foundNotification.title || 'No Title'}</dd>
<dt>Text</dt> <dt>Text</dt>
<dd>{notification.text || 'No Text'}</dd> <dd>{foundNotification.text || 'No Text'}</dd>
<dt>Created</dt> <dt>Created</dt>
<dd>{Moment(notification.createdAt).toLocaleString()}</dd> <dd>{Moment(foundNotification.createdAt).toLocaleString()}</dd>
<dt>Start</dt> <dt>Start</dt>
<dd>{Moment(notification.startAt).toLocaleString() || 'No Start Time'}</dd> <dd>{Moment(foundNotification.startAt).toLocaleString() || 'No Start Time'}</dd>
<dt>Stop</dt> <dt>Stop</dt>
<dd>{Moment(notification.stopAt).toLocaleString() || 'No End Time'}</dd> <dd>{Moment(foundNotification.stopAt).toLocaleString() || 'No End Time'}</dd>
</dl> </dl>
<button onClick={this.deleteNotification}>DELETE</button> <button onClick={deleteNotification}>DELETE</button>
</div>; </div>
}, );
};
render(){ return (
return <div className='notificationLookup'> <div className='notificationLookup'>
<h2>Lookup</h2> <h2>Lookup</h2>
<input type='text' value={this.state.query} onChange={this.handleChange} placeholder='notification key' /> <input
<button onClick={this.lookup}> type='text'
value={query}
onChange={handleChange}
placeholder='notification key'
/>
<button onClick={lookup}>
<i className={cx('fas', { <i className={cx('fas', {
'fa-search' : !this.state.searching, 'fa-search': !searching,
'fa-spin fa-spinner' : this.state.searching, 'fa-spin fa-spinner': searching,
})} /> })} />
</button> </button>
{this.state.error {error && <div className='error'>{error.toString()}</div>}
&& <div className='error'>{this.state.error.toString()}</div>
}
{this.state.foundNotification {foundNotification
? this.renderFoundNotification() ? renderFoundNotification()
: <div className='noNotification'>No notification found.</div> : <div className='noNotification'>No notification found.</div>
} }
</div>; </div>
} );
}); };
module.exports = NotificationLookup; module.exports = NotificationLookup;

View File

@@ -1,19 +1,16 @@
const React = require('react'); const React = require('react');
const createClass = require('create-react-class');
const NotificationLookup = require('./notificationLookup/notificationLookup.jsx'); const NotificationLookup = require('./notificationLookup/notificationLookup.jsx');
const NotificationAdd = require('./notificationAdd/notificationAdd.jsx'); const NotificationAdd = require('./notificationAdd/notificationAdd.jsx');
const NotificationUtils = createClass({ const NotificationUtils = () => {
displayName : 'NotificationUtils', return (
<>
render : function(){
return <>
<NotificationAdd /> <NotificationAdd />
<hr /> <hr />
<NotificationLookup /> <NotificationLookup />
</>; </>
} );
}); };
module.exports = NotificationUtils; module.exports = NotificationUtils;