feat: integrate Sonner for error handling in JSON tool
- Replaced error state management with Sonner toast notifications for JSON validation feedback. - Added success notifications for minifying and prettifying JSON. - Cleaned up the code by removing the Alert component related to error display.
This commit is contained in:
@@ -2,21 +2,20 @@ import { useState, type FC } from "react";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const Tool: FC = () => {
|
||||
const [json, setJson] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
const validateJson = () => {
|
||||
try {
|
||||
JSON.parse(json);
|
||||
setError("");
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
setError(error.message);
|
||||
toast.error(error.message);
|
||||
} else {
|
||||
setError("Invalid JSON");
|
||||
toast.error("Invalid JSON");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -26,32 +25,23 @@ const Tool: FC = () => {
|
||||
if (!validateJson()) return;
|
||||
const formattedJson = JSON.stringify(JSON.parse(json), null, 0);
|
||||
setJson(formattedJson);
|
||||
toast.success("Minified successfully");
|
||||
};
|
||||
|
||||
const prettifyJson = () => {
|
||||
if (!validateJson()) return;
|
||||
const formattedJson = JSON.stringify(JSON.parse(json), null, 2);
|
||||
setJson(formattedJson);
|
||||
toast.success("JSON prettified successfully");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col gap-4">
|
||||
<Textarea className="flex-1 w-full resize-none" placeholder="Enter your JSON here" value={json} onChange={(e) => {
|
||||
setJson(e.target.value);
|
||||
setError("");
|
||||
}} />
|
||||
<Textarea className="flex-1 w-full resize-none" placeholder="Enter your JSON here" value={json} onChange={(e) => setJson(e.target.value)} />
|
||||
<div className="flex flex-row gap-2">
|
||||
<Button onClick={validateJson}>Validate</Button>
|
||||
<Button onClick={minifyJson}>Minify</Button>
|
||||
<Button onClick={prettifyJson}>Pretty</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>Error</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user