I’ll explain in simple language.
I’ve created an eCommerce React App, I made login/signup feature using Firebase, I’m adding Product items to the <Cart />
component (just like every shopping site), everything is working fine BUT NOW I wanna add the product items that user added to his/her cart to the firebase.
This is only for the registered users, which means if the user adds products to the cart it will get stored on firebase and after some time when he/she logs in back, the cart remains the same with the product they added to their cart.
Note: This feature is not for unregistered users as the functionality of adding/removing items is already working fine.
So that’s how I’m getting which user is logged in to the app using firebase, here is the code:-
//App.js
import Header from "./components/Header/Header";
import Cart from "./pages/Cart";
import Profile from "./pages/Profile";
import { auth} from "./firebase";
function App() {
const [profileUser, setProfileUser] = useState();
const [userName, setUserName] = useState(null);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
setUserName(user.displayName);
setProfileUser(user);
console.log(user);
} else {
setUserName(null);
}
});
}, [userName]);
return (
<div>
<Header loggedUser={userName} />
<MainWrapper>
<Routes>
<Route path="/cart" element={<Cart />} />
<Route path="/profile" element={<Profile loggedUser={profileUser}/>} />
</Routes>
</MainWrapper>
</div>
);
}
2
Answers
For every user, create a sub-collection called "cart".
And inside "cart", create a document for every items.
It’ll look something like this (I used orders instead of cart).
For the query part,
For making a cart which is dependent on user login follow these 3 steps —
STEP 1. Get userData from a collection of "users" and this collection stores the cart for each user and simply set this cart to our redux cartSlice
STEP 2. Now make 2 following functions inside cartSlice.js (redux thunk pattern)
addToCart — add product to cartSlice and firebase at the same time
removeFromCart — remove product from cartSlice and firebase at the same time
STEP 3. Now simply use this functions to add and remove cartItems these functions add or remove cartItems from cartSlice and firebase at same time.