How do I save , retrieve and delete Firebase user data in local storage?
Hey there! 👋 I’m Hamza Ali, and I’m excited to share with you a streamlined approach to managing user authentication in React applications. In this blog post, we’ll dive into using local storage to persist user data, ensuring a seamless experience for your users.
Let’s get started by examining two crucial functions: setUserLocalStorage
and getUserLocalStorage
. These functions handle the storage and retrieval of user data in the local storage of the browser.
const setUserLocalStorage = (user: any) => {
localStorage.setItem('user', JSON.stringify(user));
};
const getUserLocalStorage = () => {
const userJSON = localStorage.getItem('user');
return userJSON ? JSON.parse(userJSON) : null;
};
The setUserLocalStorage
function takes a user object, converts it to a JSON string, and stores it in local storage under the key 'user'
. Conversely, getUserLocalStorage
retrieves the user data from local storage, parses it back into an object, and returns it.
Now, let’s optimize our React component using the useEffect
hook to manage user authentication seamlessly.
useEffect(() => {
const storedUser = getUserLocalStorage();
if (storedUser) {
setUser(storedUser);
} else {
// here you can redirect user on login page useing useRouter();
}
}, []);
In this useEffect
, we retrieve the user data from local storage when the component mounts. If a user exists, we set the user state accordingly. Otherwise, we redirect the user to the login page using React Router.
Additionally, we want to ensure that any changes to the user state are reflected in the local storage.
useEffect(() => {
if (user) {
setUserLocalStorage(user);
}
}, [user]);
Here, we use another useEffect
to monitor changes to the user
state. Whenever the user
state updates, we update the local storage accordingly, ensuring that the user data is always up-to-date.😊🚀
We’ll clear the user data from local storage upon successful sign-out:
const [user, setUser] = useState(null);const clearUserLocalStorage = () => {localStorage.removeItem('user');};// add in signout function clearUserLocalStorage();
setUser(null);