Displaying the relevant options in the header

At the moment, the Header component shows the Sign Up and Sign Out options, but the Sign In option is only relevant if the user hasn't signed in. The Sign Out option is only relevant if the user is authenticated. Let's clean this up in Header.tsx in the following steps:

  1. We'll start by importing the authentication context Hook:
import { useAuth } from './Auth';
  1. Let's Hook into the authentication context and return the user object, whether the user is authenticated, and whether the context has loaded just before the JSX is returned:
export const Header: FC<RouteComponentProps> = ( ... ) => {
...
const { isAuthenticated, user, loading } = useAuth();

return (
...
);
};
  1. We can use the loading and isAuthenticated properties to show the relevant options in the JSX:
<div ...>
<Link ...>
Q & A
</Link>
<form onSubmit={handleSearchSubmit}>
...
</form>
<div>
{!loading &&
(isAuthenticated ? (
<div>
<span>{user!.name}</span>
<Link
to={{ pathname: '/signout', state: { local: true } }}
css={buttonStyle}
>
<UserIcon />
<span>Sign Out</span>
</Link>
</div>
) : (
<Link to="/signin" css={buttonStyle}>
<UserIcon />
<span>Sign In</span>
</Link>
))}
</div>
</div>

We use a short circuit expression to ensure the Sign In and Sign Out buttons can't be accessed while the context is loading. We use a ternary expression to show the username and the Sign Out button if the user is authenticated and the Sign In button if not.

  1. Let's give this a try by first making sure the frontend and backend are running. We should see the Sign In and Sign Up buttons before the user has signed in:

  1. Click the Sign In button and authenticate as a user. We should see the username and a Sign Out button after the user has been authenticated:

That completes the changes needed in the Header component.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.142.69