Реагируйте с Firebase - отправка данных формы Formik - PullRequest
9 голосов
/ 17 мая 2019

У меня есть приложение реагирования, которое использует Formik для форм и Cloud Firestore для базы данных.

Я пытаюсь сохранить данные форм в Cloud Firestore.Я не получаю ошибок в своей консоли или инструментах реагирования на реагирование, и когда я нажимаю кнопку отправки, я вижу в инструменте реагирования на реагирование, что кнопка отключается, а затем снова включается, но форма не очищает данные, а данные -не отправляется в Cloud Firestore.

Моя функция handleSubmit имеет:

handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value),
        preregisterPlatform: formState.preregisterPlatform.value,
        resourceRequests: formState.resourceRequests.map(t => t.value),
        resourceOffers: formState.resourceOffers.map(t => t.value),
        ethicsIssue: formState.ethicsIssue.map(t => t.value),
        disclosureStatus: formState.disclosureStatus.value,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log("formvalues", payload);

    fsDB
      .collection("project")
      .add(payload)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };

Моя кнопка отправки имеет:

<div className="form-group">
                            <Button
                                variant="outline-primary"
                                type="submit"
                                id="ProjectId"
                                onClick={handleSubmit}
                                disabled={!dirty || isSubmitting}
                            >
                                Save
                            </Button>
                        </div>

Форма длинная - содержит 39 вопросовЯ могу видеть из своего использования данных Cloud Firestore, что я не близко к пределам для чтения и записи.Я не знаю, как измерить размер отправляемых данных моей формы, чтобы узнать, превышают ли данные формы облачные хранилища Firestore - есть ли способ заставить Firestore сообщить вам, почему отправка не работает?

Мой журнал консоли, чтобы увидеть полезную нагрузку в handleSubmit, не работает - поэтому я думаю, что должна быть другая проблема - я просто не могу найти информацию о том, в чем может быть проблема.

У кого-нибудь была проблема с длинными формами, не публикуемыми в Cloud Firestore?Если я оставлю только первые 10 вопросов, эта форма будет отправлена ​​в базу данных.

Я думаю, что у меня все в пределах моих ограничений использования пожарного депо:

enter image description here

СЛЕДУЮЩАЯ ПОПЫТКА

Итак, я вынул каждый из вопросов 11-39 из формы и прокомментировал все проверки Yup.Я добавлял вопросы по одному за раз и обнаружил, что форма работает и отправляет сообщения в FireStore, пока я не прокомментировал проверки.Они все проходят - ошибок нет.Итак - теперь мне интересно, считается ли время, затрачиваемое на их проверку, пожарным хранилищем для его процесса, и, может быть, это вызывает тайм-аут?Это возможно?Если да, есть ли способ получить указание от Firestore, что это проблема?Мои валидации приведены ниже.

Я пытался комментировать, а затем раскомментировать валидации в партиях по 10. Форма успешно отправляется, если я прокомментирую все валидации от видео до конца.В этих проверках нет ошибок.Я просто не могу получить их, а также успешно разместить в базе данных.

<Formik
            initialValues={initialValues}
            validationSchema={Yup.object().shape({
                title: Yup.string().required("Give your proposal a title"),
                subtitle: Yup.string().required("Now a subtitle"),
                fieldOfResearch: Yup.array().required("What is your field of research?"),
                disclosureStatus: Yup.string().nullable().required("Some projects are sensitive. Choose a disclosure setting."),
                overview: Yup.string().required("Outline your proposal"),
                objective: Yup.string().required("What is your objective?"),
                currentThinking: Yup.string().required("Outline the current thinking"),
                innovationStatement: Yup.string().required("If this proposal progresses previous research, what are the next steps that are being considered? If it is a paradigm shift, what has prompted it?"),
                influence: Yup.string().required("How is this proposal influenced by prevailing opinion?"),
                layperson: Yup.string().required("How would you describe this research to someone new to your field?"),
                elevator: Yup.string().required("Give it a try."),
                // video:
                resourcesConfirmation: Yup.string().required("Do you have access to research infrastructure you will need?"),
                participantPlan: Yup.string().required("Do you have a plan for how you will recruit participants for this research proposal? If your study does not require participants, then NA will do the job here."),
                resourceRequests: Yup.array().required('What sort of resources are you seeking?'),
                resourceOffers: Yup.array().required('What sort of resources will you bring to this project?'),
                technique: Yup.string().required("Ideally, this answer looks something close to 'Yes, because...' or a 'No, but this team is amazing and will master these techniques in no time, because...'"),
                pitfalls: Yup.string().required("If you've tried to look at this objectively, and can't see any pitfalls, then 'Not Applicable' will do here."),
                community: Yup.string().required("It can be a good idea to do this. If you do, you'll show sensitivity to the interests of others in your field and may open doors for potential collaborations and translation opportunities."),
                samplesize: Yup.string().required("These questions address research quality issues that funders are assessing in considering a proposal."),
                methodDescription: Yup.string().required("What approach will you take in this research?"),
                qualityControls: Yup.string().required("What controls will you put in place? These should address participants, comparators and any interventions."),
                sopAdoption: Yup.string().required("Describe at a summary level, any part of the Statement of Procedures that you have proposed that is noteworthy for reviewers."),
                participantNotification: Yup.string().required("Will you notify participants (if there are any) about the outcomes of this research? If so, describe how that will be done."),
                preregisterPlatform: Yup.string().nullable().required("Select preregistration intention"),
                teamOverview: Yup.string().required("Summarise the collective capabilities and experience of the team making this proposal"),
                proposalLead: Yup.string().required("Enter the name of the team leader"),
                indigenous: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                teamSkillGap: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                performanceIndicators: Yup.string().required("Either outline the performance indicators or mark this field 'Not Applicable'"),
                timeline: Yup.string().required("Either outline the milestones or mark this field 'Not Applicable'"),
                confirmationTeamLead: Yup.boolean().oneOf(
                    [true],
                    "Confirmation that you and each team member has reviewed each of the applicable policies is required"
                ),
                outcomeOverview: Yup.string().required("How might your study contribute to knowledge in the field?"),
                potentialApplications: Yup.string().required("Do you have any insight into potential applications for this research?"),
                potentialResearchAngles: Yup.string().required("Are there any tangential research questions that you think might follow from this study?"),
                budget: Yup.string().required("Attach a link to your project budget?"),
                ethicsIssue: Yup.array().required("Complete your ethics assessment"),
                ethicsManagementPlan: Yup.string().required("Add an ethics management plan, or if there are no issues, complete this field with 'Not Applicable'"),
                conflict: Yup.string().required("Are there any conflicts of interest?"),
                reproducibility: Yup.string().required("How will you approach reproducibility?"),
            })}

Ответы [ 2 ]

0 голосов
/ 24 мая 2019
My console log to see the payload in the handleSubmit isn't running...
  • Это важно.Это означает, что проблема в Formik.Не в Firebase.

  • Прокомментируйте часть fsDB.Оберните блок handleSubmit в try / catch и console.log части try и console.error части catch.Кроме того, добавьте console.log перед объявлением полезной нагрузки.Полученная вами информация должна объяснить причину проблемы.

Для отладки я имею в виду заменить handleSubmit на:

handleSubmit = (formState, { resetForm }) => {
    try {
        console.log('TRY');
        // Now, you're getting form state here!
        const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value),
        preregisterPlatform: formState.preregisterPlatform.value,
        resourceRequests: formState.resourceRequests.map(t => t.value),
        resourceOffers: formState.resourceOffers.map(t => t.value),
        ethicsIssue: formState.ethicsIssue.map(t => t.value),
        disclosureStatus: formState.disclosureStatus.value,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
          }
          console.log("formvalues", payload);

        /*
        fsDB
          .collection("project")
          .add(payload)
          .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
          })
          .catch(error => {
        console.error("Error adding document: ", error);
          });
        */

    } catch (reason) {
           console.error('CATCH', reason)
    }
  };
0 голосов
/ 22 мая 2019

Я ставлю свои деньги на то, что в объекте, который вы отправляете в пожарный магазин, есть несколько полей (вопрос 11-39), в которых содержится значение undefined или null.

Попробуйте очистить эти неопределенные значенияперед отправкой в ​​firestore, потому что Firestore не сохранит значение undefined и выдаст ошибку.

// You can send this to firestore.
const payload = {
  a: 1,
  b: 'text value',
  c: [{ id: 432 }]
}

// You canNOT send this to firestore.
const payload = {
  a: 1,
  b: undefined,
  c: [{ id: 432 }]
}
...