Fakultas Ilmu Komputer UI

index.tsx 3.69 KB
Newer Older
1
import React, { FC, useState, useEffect } from 'react';
2
import { View } from 'react-native';
3
import { useNavigation } from '@react-navigation/native';
4

5
import { WizardContainer, Toast } from 'components/core';
6
import { MultipleChoice, MultipleCheckbox } from 'components/form';
7
import CACHE_KEYS from 'constants/cacheKeys';
8
import * as ROUTES from 'constants/routes';
9
import { useForm } from 'hooks';
10
import { createDietProfileApi } from 'services/dietelaQuiz';
11
12
13
14
15
16
17
18
import { layoutStyles } from 'styles';

import { BiodataForm } from './components';
import {
  allAccessQuestions,
  initialValues,
  textFields,
  radioButtonGroups,
19
  fieldValidations,
20
  convertPayload,
21
} from './schema';
22
import { generateValidationSchema } from 'utils/form';
23
import { setCache } from 'utils/cache';
24
25

const AllAccessQuestionnaire: FC = () => {
26
27
28
29
30
31
32
  const navigation = useNavigation();

  const [currentPage, setCurrentPage] = useState(1);

  const {
    getTextInputProps,
    getFormFieldProps,
33
34
    isFieldError,
    isFormUntouched,
35
    handleSubmit,
36
    isSubmitting,
37
38
    values: formValues,
    setFieldValue,
39
  } = useForm({
40
    initialValues,
41
    validationSchema: generateValidationSchema(fieldValidations),
42
43
    onSubmit: async (values) => {
      const response = await createDietProfileApi(convertPayload(values));
44

45
      if (response.success) {
46
        setCache(CACHE_KEYS.dietProfileId, response.data?.id);
47
        navigation.navigate(ROUTES.dietelaQuizResult, response.data);
48
49
50
51
52
53
54
      } else {
        Toast.show({
          type: 'error',
          text1: 'Gagal menyimpan data',
          text2: 'Terjadi kesalahan pada sisi kami. Silakan coba lagi',
        });
      }
55
    },
56
57
  });

58
59
60
61
62
63
64
65
66
67
  const isCurrentPageError = (): boolean => {
    if (currentPage === 1) {
      const fields = [...textFields, ...radioButtonGroups];
      return (
        isFormUntouched() ||
        fields.reduce(
          (acc: boolean, item) => acc || isFieldError(item.name),
          false,
        )
      );
68
    }
69
70
71
    const fieldPage = currentPage - (formValues.gender === 1 ? 1 : 2);
    const fieldName = allAccessQuestions[fieldPage].fieldName;
    return isFieldError(fieldName);
72
73
  };

74
75
76
77
78
79
80
81
  const questions = allAccessQuestions.slice(formValues.gender === 1 ? 1 : 0);

  useEffect(() => {
    if (formValues.gender === 1) {
      setFieldValue('special_condition', 1);
    }
  }, [formValues.gender, setFieldValue]);

82
83
  return (
    <WizardContainer
84
85
      currentStep={currentPage}
      setCurrentStep={setCurrentPage}
86
87
88
      onFinish={handleSubmit}
      isLoading={isSubmitting}
      isNextDisabled={isCurrentPageError()}
89
90
      components={[
        <BiodataForm
91
92
93
94
95
96
97
98
          textFields={textFields.map((fieldProps) => ({
            ...fieldProps,
            ...getTextInputProps(fieldProps.name),
          }))}
          radioButtonGroups={radioButtonGroups.map((fieldProps) => ({
            ...fieldProps,
            ...getFormFieldProps(fieldProps.name),
          }))}
99
        />,
100
        ...questions.map((question, i) => {
101
102
103
104
105
106
107
108
109
110
          const FormField = question.multiple
            ? MultipleCheckbox
            : MultipleChoice;

          return (
            <View style={layoutStyles}>
              <FormField
                key={`allAccessQn${i}`}
                questionNumber={i + 1}
                questionLabel={question.questionLabel}
111
                totalQuestions={questions.length}
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
                helperText={question.helperText}
                choices={question.choiceList.map((choice, choiceId) => ({
                  label: choice,
                  value: choiceId + 1,
                }))}
                {...getFormFieldProps(question.fieldName)}
              />
            </View>
          );
        }),
      ]}
    />
  );
};

export default AllAccessQuestionnaire;