Let's carry out the following steps to implement submission on the ask form:
- 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.
- 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';
- 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.
- 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.