Only allowing authenticated users to answer a question

Let's focus on the QuestionPage component now and only allow an answer to be submitted if the user is authenticated:

  1. We'll start by importing the authentication Hook in QuestionPage.tsx:
import { useAuth } from './Auth';
  1. Let's Hook into the authentication context and return whether the user is authenticated just before the JSX is returned:
export const QuestionPage: ... = ( ... ) => {
...

const { isAuthenticated } = useAuth();

return (
...
);
};
  1. We can then use the isAuthenticated property and a short-circuit operator to only render the answer form if the user is signed in:
<AnswerList data={question.answers} />
{isAuthenticated && (
<div
...
>
<Form
submitCaption="Submit Your Answer"
...
>
...
</Form>
</div>
)}
  1. Let's give this all a try in the running app. Make sure the user is signed out and go to the question page:

There is no answer form, as we expect.

  1. Let's sign in and go to the question page again:

The answer form is available, as we expect.

That completes the changes to the question page.

In the next section, we are going to interact with the REST API endpoints that require an authenticated user to perform tasks such as submitting a question. 

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

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