77 lines
1.6 KiB
TypeScript
77 lines
1.6 KiB
TypeScript
import { FormEvent } from 'react';
|
|
|
|
export const useActions = ({
|
|
viewState,
|
|
setIsAddLoveOpened,
|
|
setIsLoading,
|
|
setAddLoveMessage,
|
|
}) => {
|
|
const toggleLoveMenu = () => {
|
|
setIsAddLoveOpened((prev) => !prev);
|
|
};
|
|
|
|
const addPoint = async (ev: FormEvent<HTMLFormElement>) => {
|
|
ev.preventDefault();
|
|
|
|
if (!ev.currentTarget.reportValidity()) {
|
|
return;
|
|
}
|
|
|
|
setIsLoading(true);
|
|
|
|
const formData = new FormData(ev.currentTarget);
|
|
const location = formData.get('location');
|
|
const comment = formData.get('comment');
|
|
|
|
const body: { [key: string]: any } = {
|
|
location: location.toString(),
|
|
};
|
|
|
|
if (comment && comment.toString().length > 0) {
|
|
body.comment = comment.toString();
|
|
}
|
|
|
|
const token = localStorage.getItem('token');
|
|
|
|
const { latitude, longitude } = viewState;
|
|
|
|
const point = {
|
|
type: 'Point',
|
|
coordinates: [longitude, latitude],
|
|
};
|
|
|
|
body.geopoint = point;
|
|
|
|
try {
|
|
const request = await fetch('/api/point', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: token,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
if (request.status == 403) {
|
|
setIsLoading(false);
|
|
setAddLoveMessage('Reconnectez-vous pour réessayer');
|
|
return;
|
|
}
|
|
if (request.status == 400) {
|
|
setIsLoading(false);
|
|
setAddLoveMessage('Erreur interne. Veuillez réessayer');
|
|
return;
|
|
}
|
|
|
|
setIsLoading(false);
|
|
setIsAddLoveOpened(false);
|
|
} catch (error) {
|
|
console.error(error);
|
|
setAddLoveMessage('Erreur interne. Veuillez réessayer');
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
return { toggleLoveMenu, addPoint };
|
|
};
|