Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const useSettingsManagement = () => {
const app = useAppBridge();
const [isLoading, setIsLoading] = useState(true);
const [isSetLoading, setIsSetLoading] = useState(false);
const [settingsObj, setSettingsObj] = useState(undefined);
const [error, setError] = useState(undefined);
useEffect(() => {
getSettings();
}, []);
const getSettings = async () => {
setIsLoading(true);
try {
const token = await getSessionToken(app);
const res = await fetch("/settings", {
headers: { Authorization: `Bearer ${token}` },
});
const responseData = await res.json();
if (responseData.status === "EMPTY_SETTINGS") {
return;
}
if (responseData.status === "OK_SETTINGS") {
setSettingsObj(responseData.data);
return;
}
throw Error("Unknown settings status");
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false);
}
};
const setSettings = async (productId) => {
setIsSetLoading(true);
try {
const token = await getSessionToken(app);
const res = await fetch("/settings", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-type": "text/plain",
},
body: JSON.stringify({ productId }),
});
const responseData = await res.json();
if (responseData.status === "OK_SETTINGS") {
setSettingsObj(responseData.data);
}
throw Error("Unknown settings status");
} catch (err) {
setError(err.message);
} finally {
setIsSetLoading(false);
}
};
const clearError = () => setError(undefined);
return {
settingsObj,
isLoading,
error,
isSetLoading,
setSettings,
clearError,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment