Reputation: 643
I am trying to conditional rendering when state is undefined, and i would like to show a sweetalert to show the user that he has not selected a client. But i am receiving this error:
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Snippet:
const location = useLocation();
const ClientNotSelected = () => {
return (
<div>
{
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})
}
</div>
)
}
if (location.state === undefined) {
return <ClientNotSelected />;
}
Upvotes: 0
Views: 518
Reputation: 643
HOW I SOLVED IT:
I have created
const [clientSelected, setClientSelected] = useState(false);
and i checked it in the useEffect, with swal.fire inside here it doesnt give any problems/errors
useEffect(()=>{
if (location.state === undefined){
setClientSelected(false);
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
history.goBack();
}
})
}
else{
setClientSelected(true);
}
})
below i have continued with the same condition but checking the new var clientSelected
if (!clientSelected) {
return <h1>Select a client</h1>;
} else {
return <Component />;
}
Upvotes: 0
Reputation: 11
There is no need to create and render a component to fire the alert.
You can move Swal.fire()
to your if statement.
Like this:
if (location.state === undefined) {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then((result) => {
if (result.isConfirmed) {
Swal.fire("Deleted!", "Your file has been deleted.", "success");
}
});
}
Upvotes: 1