Deviopath › React

Auth Provider with a useAuth Hook

Hard · Context

Build a small auth system. Goal: hide a context behind a custom hook.

Write AuthProvider (it owns the login state) and useAuth(), which returns { user, pending, error, login, logout }. Header, LoginForm and MembersArea use useAuth() instead of props. fakeLogin(name, password) resolves after 150ms when the password is "secret" and rejects otherwise.

- Header: <span className="user">Guest</span>, or "Hi, Ana" plus a "Log out" button when logged in.

- LoginForm, only while logged out: <input name="username">, <input name="password"> and "Log in". While waiting show <p className="status">Signing in...</p> and disable the button. A failure shows <p className="error">Wrong password</p>.

- MembersArea: <p className="members">Welcome, Ana</p> or "Please log in".

The name is trimmed.

Next: Cart with Context and Reducer