Public Access
fix(settings): keep the language and save settings one after the other
This commit is contained in:
1 parent
14dd59f9e0
commit
f605917874
25 files changed
+423
-98
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import {apiFetch} from './api.js';
|
||||
|
||||
export const LANGUAGES = ['en', 'de'];
|
||||
|
||||
const LANGUAGE_STORAGE_KEY = 'tbp_language';
|
||||
export const REQUEST_TIMEOUT_MS = 10000;
|
||||
|
||||
export const readCachedLanguage = () => {
|
||||
try {
|
||||
const stored = localStorage.getItem(LANGUAGE_STORAGE_KEY);
|
||||
return LANGUAGES.includes(stored) ? stored : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const cacheLanguage = (language) => {
|
||||
try {
|
||||
localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
|
||||
} catch {
|
||||
// Private mode or a full storage: the language is only not cached.
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* GET /api/users/me on Auth. The caller handles the response status.
|
||||
*/
|
||||
export const fetchMe = () => apiFetch(`${import.meta.env.VITE_API_URL}/api/users/me?v=1`, {
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
let queue = Promise.resolve();
|
||||
|
||||
/**
|
||||
* PUT /api/users/settings on Auth with `changes`. That endpoint replaces all four fields, so each save first loads
|
||||
* the saved ones; saves run one after another, from every page. The caller handles the response status.
|
||||
*/
|
||||
export const saveSettings = (changes) => {
|
||||
const save = async () => {
|
||||
const me = await fetchMe();
|
||||
if (!me.ok) return me;
|
||||
const data = await me.json();
|
||||
return apiFetch(`${import.meta.env.VITE_API_URL}/api/users/settings`, {
|
||||
method: 'PUT',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
useDarkTheme: !!data.settings?.useDarkTheme,
|
||||
language: data.settings?.language ?? '',
|
||||
displayName: data.displayName ?? null,
|
||||
publicProfile: !!data.settings?.publicProfile,
|
||||
...changes,
|
||||
}),
|
||||
// A hung request must not hold back the next saves.
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
};
|
||||
const result = queue.then(save, save);
|
||||
queue = result.catch(() => {});
|
||||
return result;
|
||||
};
|
||||
Reference in new issue
Block a user