Forms and Local States in Redux
In previous lessons, we learned how to get data from the store and display it in a React component. In this lesson we will begin adding new data. We will do this using a form, by filling out which the seller will be able to add a new product.
Let's start with the fact that it doesn't always make sense to use the global Redux state. There are cases when we can create local states for our needs. We will call local states states that are used inside a certain component for technical needs. For example, to hide or show something by pressing a button.
In our case, the user will enter data into the form and, naturally, we will need states for this. We could use a global Redux state, but this does not make sense, since our states will only work in one place in the application for the product addition form. The main rule to follow is that local states cannot work outside the component in which they are created, and in no case should they touch the store. This practice is often used when creating forms.
Let's open the products folder of our product app, create a NewProductForm.jsx file in it and import the useState hook into it:
import { useState } from 'react'
Now let's create the component itself with the form and write the usual states in it, as we did before in React. We need states to work with the name, description, price and quantity of the product:
export const NewProductForm = () => {
const [name, setName] = useState('')
const [desc, setDesc] = useState('')
const [price, setPrice] = useState(0)
const [amount, setAmount] = useState(0)
}
Next, we will add standard processing for each field when the user enters data:
const onNameChanged = (e) => setName(e.target.value)
const onDescChanged = (e) => setDesc(e.target.value)
const onPriceChanged = (e) => setPrice(e.target.value)
const onAmountChanged = (e) => setAmount(e.target.value)
And then we return the layout with the heading and empty form to the component:
return (
<div>
<h2>Add a New Product</h2>
<form>
</form>
</div>
)
Open your application with students. Create a file NewStudentForm.jsx in the folder students. In the component NewStudentForm create local states for the fields you need, write processing for each field as shown in the lesson.
Return the NewStudentForm component layout containing a title and an empty form.