// Provider component that wraps your app and makes auth object ... // ... available to any child component that calls useAuth(). exportfunctionProvideAuth({ children }) { const auth = useProvideAuth(); return<authContext.Providervalue={auth}>{children}</authContext.Provider>; }
// Hook for child components to get the auth object ... // ... and re-render when it changes. exportconstuseAuth = () => { returnuseContext(authContext); };
// Provider hook that creates auth object and handles state functionuseProvideAuth() { const [user, setUser] = useState(null);
// Wrap any Parse methods we want to use making sure ... // ... to save the user to state. constsignin = (username, password) => { returnParse.User .logIn(username, password) .then(currentUser => { setUser(currentUser); return currentUser; }); };
// Subscribe to user on mount // Because this sets state in the callback it will cause any ... // ... component that utilizes this hook to re-render with the ... // ... latest auth object. useEffect(() => { Parse.User .currentAsync() .then(currentUser => { if (currentUser) { setUser(currentUser); } else { setUser(false); } });