Implementing form submission in the answer form

Let's carry out the following steps to implement a submission on the answer form:

  1. In QuestionsData.tslet's create a function to simulate posting an answer:
export interface PostAnswerData {
questionId: number;
content: string;
userName: string;
created: Date;
}

export const postAnswer = async (
answer: PostAnswerData,
): Promise<AnswerData | undefined> => {
await wait(500);
const question = questions.filter(
q => q.questionId === answer.questionId,
)[0];
const answerInQuestion: AnswerData = {
answerId: 99,
...answer,
};
question.answers.push(answerInQuestion);
return answerInQuestion;
};

The function finds the question in the questions array and adds the answer to it. The remainder of the preceding code contains straightforward types for the answer to post and the function result.

  1. In QuestionPage.tsxlet's import the function we just created along with the values interface from Form.tsx:
import {
QuestionData,
getQuestion,
postAnswer
} from './QuestionsData';
import { Form, required, minLength, Values } from './Form';
  1. We can now implement the submit handler in the QuestionPage component just above the return statement:
const handleSubmit = async (values: Values) => {
const result = await postAnswer({
questionId: question!.questionId,
content: values.content,

userName: 'Fred',
created: new Date()
});

return { success: result ? true : false };
};

return ( ... )

So, this calls the postAnswer function, asynchronously passing in the content from the field values with a hardcoded user name and created date.

Notice ! after the reference to the question state variable. This is a non-null assertion operator.

A non-null assertion operator (!) tells the TypeScript compiler that the variable before it cannot be null or undefined. This is useful in situations when the TypeScript compiler isn't smart enough to figure this fact out itself.

So, ! in question!.questionId stops the TypeScript complaining that question could be null.

  1. Let's pass this handler in the onSubmit prop as well as our required success and failure messages to the Form component in the JSX:
<Form
submitCaption="Submit Your Answer"
validationRules={{
content: [
{ validator: required },
{ validator: minLength, arg: 50 }
]
}}
onSubmit={handleSubmit}
failureMessage="There was a problem with your answer"
successMessage="Your answer was successfully submitted"
>
...
</Form>

That's all of our forms complete now. We'll try them all out next.

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

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