I am building a react app with DRF, and I am trying to build some flashcards, inspired by the app Quizlet. Whenever you create a deck in Quizlet you get a form: in this you need to create a deck instance and multiple card instances which means that you need to send post requests to 2 different endpoints (I am using postgres: there are two tables
Deck: title, description, directory_id, ...
Card: side1, side2, deck_id, ...
)
My question is, how would I go about this using formik in react? Do I use multiple Formik components like this
import { Formik, Form } from "formik"
cardForms = () => {
for (i to n)
<Formik ...>
}
...
return (
{ */ formik component for deck title and description */ }
<Formik ... />
{*/ formik component for each card form */}
{cardForms}
)
It seems that it could work, however there are multiple problems with my solution. Each formik component would have a onSubmit prop. This means that I would hit the database n times (one for each card, plus the hit to create the actual deck). This is incredibly inefficient. I would like to have just two Formik
components: one for the deck and one for all the cards. But how would I go about it? Thank you for your time and consideration.
CodePudding user response:
You can use just 1 Formik context for this. Just use formik's FieldArray
component to access the individual cards. For example
assuming your initial data is something like this:
{
title: "deck title",
description: "deck description",
cards: [{
side1: "side 1",
side2: "side 2"
}]
}
<Formik>
{({ values }) => (
<Form>
<Field name="title"/>
<Field name="description"/>
<FieldArray name="cards">
{({ insert, remove, push }) => (
<div>
{
values.cards.map((card,index) => {
return <Field name={`cards.${index}.sid1`}></Field>
})
}
</div>
)})
</FieldArray>
</Form>
)}
<Formik>
More info here : https://formik.org/docs/examples/field-arrays