Formik has proven to be one of the most useful React libraries currently out there, helping to alleviate much of the headache caused by handling forms. Traditionally, the method for managing state relies on using the useState() hook for each field, adding an event listener, and then using an onChange() method to update them. Formik does all of this for you and more, greatly reducing the amount of code present. It even keeps track of whether each field has been “touched” by the user. You can find a lot of information on how to set up forms using Formik online but there isn’t a lot on combining it with fetch requests. We are going to explore that here to build a simple form.
A key aspect of Formik are the initial values. InitialValues is considered to be one of Formik’s props and is set when the form is first rendered. One assigns these to a variable (typically called initialValues) or as an attribute in the Formik tab (we will talk about this below) which contains a dictionary of key value pairs. The keys would be those variables whose values you want to post in the fetch request. You can see this in the example below.
Then, we wrap all of our form in a Form tag which plays a crucial role in integrating Formik’s form management capabilities into your React components. It establishes a context within which Formik manages form state, validation, and submission logic. A key thing that the Form tag also does is prevent the default behavior of the browser navigating away from the current page after submission.
The values given here are considered to be default values for those keys. It is important to set the default values to the same data type that you intend on posting to your database. For example, the type key has a value of an empty string because the model that this data will post to has the data type of string. Same thing with sub_price being a number, etc. Once we have declared our initial values, we can assign it to an initialValues attribute within the Formik tag as shown below.
This tells Formik that these values are going to be changed by the fields within the Formik form. Using the sub_price as an example, we wrap the Field tag in a tag named FieldContainer like so.
We give it a type of number because this value is going to be an integer, an id and name of sub_price, and then an optional className for formatting if you choose. The sub_price name tells Formik that whatever changes here should be reflected in the value with the key matching this. This is essentially a built in onChange function which would be used to manually handle state. Doing this greatly decreases the amount of code that is needed to write in order to handle all of the form fields. With each of these set up in the JSX, all that is left to do is add a button and the onSubmit={handleSubmit} attribute below the initialValues attribute shown in image 2. Then, set up a handleSubmit function such as one below, passing in values (which is the dictionary of initialValues) which are used in the body of the POST request. Values are passed into the value parameter, null which is the replace in case any of the initialValues are empty, and 2 for the spacer parameter which just increases the amount of spaces in the JSON string output for readability purposes.
We can see that the post request points to a class function in our server section. This function receives the json data and attempts to create a new entry in the Subscription database. Using the same name in both the Formik fields and here help bolster the readability of your code. It then adds and commits the changes before returning a success code of 201.
It is as easy as that. Obviously Formik can be used for much more complex state and form handling but at the barebones, basic level, this shows its power. It will also keep track of any errors that might occur using the ErrorMessage tag and the name attribute pointing at which value you want Formik to monitor.
Another great aspect of Formik is that it provides built-in support for form validation, allowing you to use Yup to define validation rules. It is designed to work well with other React libraries and patterns. Good luck coding!
Top comments (0)