Skip to content

Instantly share code, notes, and snippets.

@wirtzdan
Created December 1, 2020 21:00
Show Gist options
  • Save wirtzdan/09cb4802525348ebf381b41e069de3d6 to your computer and use it in GitHub Desktop.
Save wirtzdan/09cb4802525348ebf381b41e069de3d6 to your computer and use it in GitHub Desktop.
/**
* Get and write the user settings
*/
export const useSettings = () => {
const { authUser } = useFirestoreUser();
const [settings, setSettings] = useState("");
/* Default settings */
const defaultSettings = {
hideFloatingHelpIcon: {
isActive: false,
},
};
/* Default path to the settings subcollection */
const settingsRef = firebase
.firestore()
.collection("users")
.doc(authUser?.uid)
.collection("settings");
/* Fetch Firestore settings once, when useSettings is called */
useEffect(() => {
getSettings();
}, []);
/* Overwrite Firestore settings, everytime the settings state changes */
useEffect(() => {
updateSettings(settings);
}, [settings]);
/* Get settings from Firestore */
const getSettings = async () => {
const snapshot = await settingsRef.get();
return snapshot.docs.map((doc) => doc.data());
};
/* Update the settings in Firestore */
const updateSettings = async ({ settings }) => {
settings.map((s) => {
settingsRef.doc(s.id).update(s.data);
});
};
return {
settings,
setSettings,
defaultSettings,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment