Skip to content

Commit

Permalink
fix(SoMeInputs): remove useEffects and use proper form patches
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiazom committed Sep 2, 2024
1 parent c48a1c7 commit d2b178a
Showing 1 changed file with 21 additions and 30 deletions.
51 changes: 21 additions & 30 deletions studio/components/SoMeInputs.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from "react";
import { ObjectInputProps, PatchEvent, set } from "sanity";
import React from "react";
import { ObjectInputProps, set } from "sanity";
import { Box, TextInput, Select, Stack, Label } from "@sanity/ui";

export const SoMePlatforms: { [key: string]: string } = {
Expand All @@ -14,44 +14,35 @@ export const SoMePlatforms: { [key: string]: string } = {
tikTok: "Tiktok",
};

const detectPlatformFromUrl = (url: string): string | null => {
for (const key in SoMePlatforms) {
if (url.includes(key)) {
return SoMePlatforms[key];
}
}
return null;
};

const SoMeInputs: React.FC<ObjectInputProps<Record<string, any>>> = ({
value = {},
onChange,
}) => {
const [url, setUrl] = useState(value.url || "");
const [platform, setPlatform] = useState(value.platform || "");

useEffect(() => {
let detectedPlatform = "";
for (const key in SoMePlatforms) {
if (url.includes(key)) {
detectedPlatform = SoMePlatforms[key];
break;
}
}
setPlatform(detectedPlatform);
if (onChange) {
onChange(
PatchEvent.from([set({ ...value, url, platform: detectedPlatform })]),
);
}
}, [url, onChange]);

const handleUrlChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (!onChange) return;
const newUrl = event.target.value;
setUrl(newUrl);
onChange(set(newUrl, ["url"]));
const detectedPlatform = detectPlatformFromUrl(newUrl);
if (detectedPlatform !== null) {
onChange(set(detectedPlatform, ["platform"]));
}
};

const handlePlatformChange = (
event: React.ChangeEvent<HTMLSelectElement>,
) => {
if (!onChange) return;
const newPlatform = event.target.value;
setPlatform(newPlatform);
if (onChange) {
onChange(
PatchEvent.from([set({ ...value, url, platform: newPlatform })]),
);
}
onChange(set(newPlatform, ["platform"]));
};

return (
Expand All @@ -60,7 +51,7 @@ const SoMeInputs: React.FC<ObjectInputProps<Record<string, any>>> = ({
<Stack space={3}>
<Label>URL</Label>
<TextInput
value={url}
value={value.url}
onChange={handleUrlChange}
placeholder="Enter URL"
/>
Expand All @@ -69,7 +60,7 @@ const SoMeInputs: React.FC<ObjectInputProps<Record<string, any>>> = ({
<Box>
<Stack space={3}>
<Label>Platform</Label>
<Select value={platform} onChange={handlePlatformChange}>
<Select value={value.platform} onChange={handlePlatformChange}>
<option value="">Select Platform</option>
{Object.values(SoMePlatforms).map((platform) => (
<option key={platform} value={platform}>
Expand Down

0 comments on commit d2b178a

Please sign in to comment.