Implementing form submission in the ask form

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

  1. In QuestionsData.ts, let's create a function to simulate posting a question:
export interface PostQuestionData {
title: string;
content: string;
userName: string;
created: Date;
}

export const postQuestion = async (
question: PostQuestionData,
): Promise<QuestionData | undefined> => {
await wait(500);
const questionId =
Math.max(...questions.map(q => q.questionId)) + 1;
const newQuestion: QuestionData = {
...question,
questionId,
answers: [],
};
questions.push(newQuestion);
return newQuestion;
};

The function adds the question to the questions array using the Math.max method to set questionId to the next number.

  1. In AskPage.tsx, let's import the function we just created along with the values interface from Form.tsx:
import { Form, required, minLength, Values } from './Form';
import { postQuestion } from './QuestionsData';
  1. We can now implement the submit handler in the AskPage component:
export const AskPage = () => {
const handleSubmit = async (values: Values) => {
const question = await postQuestion({
title: values.title,
content: values.content,
userName: 'Fred',
created: new Date()
});

return { success: question ? true : false };
};
return (
...
);
};

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

  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 Question"
validationRules={{
title: [{ validator: required }, { validator: minLength, arg: 10 }],
content: [{ validator: required }, { validator: minLength, arg: 50 }]
}}
onSubmit={handleSubmit}
failureMessage="There was a problem with your question"
successMessage="Your question was successfully submitted"
>
...
</Form>

That completes the implementation of the ask form. We'll try it out after we've implemented the answer form.

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

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