Created
December 1, 2020 21:00
-
-
Save wirtzdan/09cb4802525348ebf381b41e069de3d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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