Skip to content

Commit

Permalink
Add promisification for send new message
Browse files Browse the repository at this point in the history
  • Loading branch information
AxeRicin committed Dec 28, 2023
1 parent 3960a23 commit 5fa0245
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
22 changes: 10 additions & 12 deletions frontend/src/Components/NewMessageForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ import { AuthContext } from '../hoc/AuthProvider';
import { ApiContext } from '../hoc/ApiProvider';
import { FilterContext } from '../hoc/FilterProfanityProvider';

const msTimeout = 5000;

const NewMessageForm = ({ currentChannelID }) => {
const { user: { username } } = useContext(AuthContext);
const { t } = useTranslation();
const { socket } = useContext(ApiContext);
const { sendNewMessage } = useContext(ApiContext);
const filter = useContext(FilterContext);
const textArea = useRef();

Expand All @@ -26,17 +24,17 @@ const NewMessageForm = ({ currentChannelID }) => {
validationSchema: yup.object().shape({
body: yup.string().trim().required(),
}),
onSubmit: (values) => {
socket.timeout(msTimeout).emit('newMessage', { body: filter.clean(values.body), channelId: currentChannelID, username }, (err, response) => {
if (err) {
formik.setSubmitting(false);
return toast.error(t('notifications.connection_error'));
}
if (response.status === 'ok') {
onSubmit: async (values) => {
try {
const message = { body: filter.clean(values.body), channelId: currentChannelID, username };
await sendNewMessage(message).then(() => {
formik.values.body = '';
formik.setSubmitting(false);
}
});
});
} catch (err) {
formik.setSubmitting(false);
return toast.error(t('notifications.connection_error'));
}
},
});

Expand Down
11 changes: 10 additions & 1 deletion frontend/src/hoc/ApiProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ const ApiProvider = ({ children }) => {
const dispatch = useDispatch();
const { t } = useTranslation();

const sendNewMessage = (message) => new Promise((resolve, rejected) => {
socket.timeout(msTimeout).emit('newMessage', message, (err, response) => {
if (err) rejected(err);
else {
resolve(response);
}
});
});

const takeMessage = () => {
socket.on('newMessage', (newMessage) => dispatch(addMessage(newMessage)));
};
Expand Down Expand Up @@ -72,7 +81,7 @@ const ApiProvider = ({ children }) => {
};

const value = useMemo(() => ({
socket,
sendNewMessage,
takeMessage,
sendNewChannel,
takeChannel,
Expand Down

0 comments on commit 5fa0245

Please sign in to comment.