By project behavioral need requirements are vary on situation demand, so that for custom toast component with additional functionality with the help of react-toastify...
File ==> Service.js
import { apiCancelToast } from '../components/utils/ApiCancelBtn';
import { taskInProgress } from './memory';
import { toast } from 'react-toastify';
export class Service {
constructor( ... ... ) {
this. ... ...
}
async handleApiCall( callBack ) {
... ...
taskInProgress.status = true;
try {
toast.dismiss(); // 1st toast cancel
const data = await callBack();
if (data.id !== '') apiCancelToast(data.id);
return data;
} catch (e) {
... ...
}
}
... ...
}
File ==> ApiCancelBtn.jsx [custom cancel component]
import { taskInfoMap, taskInProgress } from '../../../memory';
import { taskTokenCalculation } from '../../../actions/dropdown';
import { useDispatch } from 'react-redux';
import { toast } from 'react-toastify';
import loading from '../../../assets/loading.gif';
import api from '../../../api';
import 'react-toastify/dist/ReactToastify.css';
function ApiCancelBtn({ taskId }) {
const dispatch = useDispatch();
const handleTaskCancel = async (taskId) => {
toast.dismiss(); // 2nd toast cancel
taskInProgress.status = false;
try {
if (taskId) {
const { consumed } = await api.ai.cancelTask(taskId);
if (consumed) dispatch(taskTokenCalculation(consumed);
taskInfoMap.delete(taskId);
}
} catch (error) {
// console.log(error);
}
};
return (
<div className="toast-custom-cancel-button">
<img src={loading} alt="loading" />
<div>
<p> Processing your request... </p>
<button onClick={() => handleTaskCancel(taskId)}>
Abort
</button>
</div>
</div>
);
}
export function apiCancelToast(taskId) {
toast.info('', {
icon: false,
pauseOnHover: true,
toastId: taskId,
autoClose: false,
draggable: false,
closeOnClick: false,
closeButton: <ApiCancelBtn taskId={taskId} />,
});
}
File ==> app.css
.toast-custom-cancel-button {
user-select: none;
display: flex;
gap: 10px;
padding: 8px 0;
}
.toast-custom-cancel-button img {
width: 20px;
height: 20px;
}
.toast-custom-cancel-button p {
font-size: 16px;
}
.toast-custom-cancel-button button {
border-radius: 10px;
padding: 10px 18px;
outline: none;
border: none;
cursor: pointer;
transition: 0.3s;
}
.toast-custom-cancel-button button:hover {
background: #e86a54 !important;
color: white;
}
Top comments (0)