Skip to content

Commit

Permalink
fix news modal from closing when image is not created (#1061) (#1062)
Browse files Browse the repository at this point in the history
  • Loading branch information
Adeodonne authored Dec 12, 2023
1 parent 8dd38dc commit 0e2c36c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 67 deletions.
16 changes: 4 additions & 12 deletions src/app/stores/news-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ export default class NewsStore {
}

public setInternalMap(news: News[]) {
// Offset in hours
// Offset in hours
const localOffset = new Date().getTimezoneOffset() / 60;
this.NewsMap.clear();
news.forEach(this.setItem);

// as date is saved in UTC+0, add local offset to actualize date
news.forEach(n => n.creationDate = dayjs(n.creationDate).subtract(localOffset, 'hours'));
news.forEach((n) => n.creationDate = dayjs(n.creationDate).subtract(localOffset, 'hours'));
}

public set setNews(news: News) {
Expand Down Expand Up @@ -86,19 +86,11 @@ export default class NewsStore {
};

public createNews = async (news: News) => {
try {
await newsApi.create(news).then((created) => this.setItem(created));
} catch (error: unknown) {
console.log(error);
}
await newsApi.create(news).then((created) => this.setItem(created));
};

public updateNews = async (news: News) => {
try {
await newsApi.update(news).then((updated) => this.setItem(updated));
} catch (error: unknown) {
console.log(error);
}
await newsApi.update(news).then((updated) => this.setItem(updated));
};

public deleteNews = async (newsId: number) => {
Expand Down
112 changes: 57 additions & 55 deletions src/features/AdminPage/NewsPage/NewsModal/NewsModal.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,23 @@ const NewsModal: React.FC<{
const [data, setData] = React.useState(initialValue ?? '');
const [count, setCount] = React.useState(0);
const [textCount, setTextCount] = useState(0);
const [actionSuccess, setActionSuccess] = useState(false);
const [waitingForApiResponse, setWaitingForApiResponse] = useState(false);

message.config({
top: 100,
duration: 2,
maxCount: 3,
prefixCls: 'my-message',
});

useEffect(() => {
setWaitingForApiResponse(false);
if (actionSuccess) {
message.info('Новину успішно додано/оновлено!', 2);
setActionSuccess(false);
}
}, [actionSuccess]);
const handlePreview = async (file: UploadFile) => {
setFilePreview(file);
setPreviewOpen(true);
Expand Down Expand Up @@ -122,19 +138,23 @@ const NewsModal: React.FC<{
};

const closeAndCleanData = () => {
form.resetFields();
setIsModalOpen(false);
setTextIsPresent(false);
setTextIsChanged(false);
editorRef.current?.setContent('');
if (!waitingForApiResponse) {
form.resetFields();
setIsModalOpen(false);
setTextIsPresent(false);
setTextIsChanged(false);
editorRef.current?.setContent('');
}
};

const closeModal = () => {
setIsModalOpen(false);
if (!waitingForApiResponse) {
setIsModalOpen(false);
}
};

dayjs.locale('uk');
const dayJsUa = require("dayjs/locale/uk"); // eslint-disable-line
const dayJsUa = require("dayjs/locale/uk") // eslint-disable-line
ukUAlocaleDatePicker.lang.shortWeekDays = dayJsUa.weekdaysShort;
ukUAlocaleDatePicker.lang.shortMonths = dayJsUa.monthsShort;

Expand All @@ -150,32 +170,25 @@ const NewsModal: React.FC<{
return true;
};

const callErrorMessage = (messageText: string) => {
message.config({
top: 100,
duration: 1,
maxCount: 3,
rtl: true,
prefixCls: 'my-message',
});
message.error(messageText);
};

const handleOk = async () => {
try {
message.loading('Валідація даних...');

await form.validateFields();
if (handleTextChange()) {
form.submit();
message.success('Новину успішно додано!', 2);
setWaitingForApiResponse(true);
await form.submit();
} else {
callErrorMessage("Будь ласка, заповніть всі обов'язкові поля");
throw new Error();
}
} catch (error) {
callErrorMessage("Будь ласка, заповніть всі обов'язкові поля");
message.error("Будь ласка, заповніть всі обов'язкові поля");
}
};

const onSuccessfulSubmitNews = async (formValues: any) => {
message.loading('Зберігання...');

const news: News = {
id: 0,
imageId: imageId.current,
Expand All @@ -190,37 +203,27 @@ const NewsModal: React.FC<{
if (formValues.title == t.title || imageId.current == t.imageId) newsItem = t;
});
// need to fix when url is static because from didn't see ti when u press save button on second time
let success = false;
if (newsItem) {
news.id = newsItem.id;
news.imageId = imageId.current;
news.image = image.current;
Promise.all([
newsStore
.updateNews(news)
.then(() => {
success = true;
})
.catch((e) => {
console.log(e);
success = false;
}),
]);
} else {
Promise.all([
newsStore
.createNews(news)
.then(() => {
success = true;
})
.catch((e) => {
console.log(e);
success = false;
}),
]);
}
if (success && afterSubmit) {
afterSubmit(news);
try {
if (!image.current) {
throw new Error("Image isn't uploaded yet");
}
if (newsItem) {
news.id = newsItem.id;
news.imageId = imageId.current;
news.image = image.current;

await newsStore.updateNews(news);
} else {
await newsStore.createNews(news);
}

if (afterSubmit) {
afterSubmit(news);
}
setActionSuccess(true);
} catch (e: unknown) {
message.error('Не вдалось оновити/створити новину. Спробуйте ще раз.');
setWaitingForApiResponse(false);
}
};

Expand All @@ -231,7 +234,7 @@ const NewsModal: React.FC<{
setCount(cCount);
setTextCount(cCount);
} else {
callErrorMessage('Ви перевищіли максимально допустиму кількість символів');
message.error('Ви перевищіли максимально допустиму кількість символів');
}
};

Expand Down Expand Up @@ -358,7 +361,6 @@ const NewsModal: React.FC<{
<Form.Item
name="image"
label="Зображення: "
rules={[{ required: true, message: 'Додайте зображення' }]}
valuePropName="fileList"
getValueFromEvent={(e: any) => {
if (Array.isArray(e)) {
Expand Down

0 comments on commit 0e2c36c

Please sign in to comment.