我正在将React与MongoDB和MongoDB Stitch无服务器后端作为服务一起使用。我已经进行了Google登录,并遵循了MongoDB教程中的教程。
https://docs.mongodb.com/stitch/tutorials/guides/todo-guide-google/
因为我希望用户也提供额外的数据。我创建了一个名为用户的自定义数据表,该表已与owner_id字段链接到登录的用户。我关注了文档,此方法工作正常。
当用户在currentuser对象上登录名为customData的属性时,该属性将包含额外的数据。但是,一旦页面刷新发生,当前用户的所有数据仍然可用,但customData对象为空。
是否可以将customData保留在currentUser上。还是MongoDB Stitch登录后仅提供一次用户的customData?
export const StitchAuthProvider = ({ children }) => {
const [authState, setAuthState] = useState({
isLoggedIn: hasLoggedInUser(),
currentUser: getCurrentUser()
});
useEffect(() => {
const authListener = {
onUserLoggedIn: (auth, loggedInUser) => {
if (loggedInUser) {
setAuthState(authState => ({
...authState,
isLoggedIn: true,
currentUser: loggedInUser
}));
if (!loggedInUser.customData._id) {
try {
users.insertOne({
owner_id: loggedInUser.id,
...loggedInUser.profile.data
});
} catch (error) {
console.error("aaaaah Ik messed up!", error);
}
}
}
},
onUserLoggedOut: (auth, loggedOutUser) => {
setAuthState(authState => ({
...authState,
isLoggedIn: false,
currentUser: null
}));
}
};
addAuthenticationListener(authListener);
handleOAuthRedirects();
setAuthState(state => ({ ...state }));
return () => {
removeAuthenticationListener(authListener);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Authentication Actions
const handleLogin = async provider => {
if (!authState.isLoggedIn) {
switch (provider) {
case "anonymous":
return loginAnonymous();
case "google":
return loginGoogle();
default: {
}
}
}
};
const handleLogout = async () => {
const { isLoggedIn } = authState;
if (isLoggedIn) {
await logoutCurrentUser();
setAuthState({
...authState,
isLoggedIn: false,
currentUser: null
});
} else {
console.log(`can't handleLogout when no user is logged in`);
}
};
const authInfo = useMemo(
() => {
const { isLoggedIn, currentUser } = authState;
// TODO: remove logger
console.log(currentUser);
const value = {
isLoggedIn,
currentUser,
actions: { handleLogin, handleLogout }
};
return value;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[authState.isLoggedIn]
);