Form for editing data in Redux
Now we have a reducer to change the data in the store. In this lesson we will create a form with which we can edit the product data.
Let's open our product app and create a file EditProductForm.jsx
in the products
folder. Creating a component EditProductForm
will be similar to NewProductForm
, except for some differences that we will focus on. So copy the entire code NewProductForm.jsx
and paste it into the created file EditProductForm.jsx
. Now let's start in order.
Remove nanoid from import, we don't need to generate id here. Replace import productAdded
with productUpdated
, because here we will use action for updating, not for adding product.
Next, we change the name of our component function from NewProductForm
to EditProductForm
.
Before we set up local states in the EditProductForm
function for name
, desc
, price
and amount
, let's add a few more lines of code. As we mentioned earlier, we don't need to generate the id here. Now our task is to get it from the data of the product being modified. We already did this when creating a separate page for the product. So, let's get the id using the useParams
hook, and then find the product we need using the useSelector
hook (don't forget to import both hooks at the top of the file):
let params = useParams()
const { productId } = params
const product = useSelector((state) =>
state.products.find((product) => product.id === productId)
)
After that, we will change the block with the declaration of local states. Now we need to set the initial value to the product data received from the store. This is how the first state will look like, rework the three remaining ones yourself:
const [name, setName] = useState(product.name)
After assigning the variable to useDispatch
, let's add one more line of code, this time for the useNavigate
hook. We'll use it to return to the product page when the user saves the changes they made to the form:
const navigate = useNavigate()
We also import this hook at the beginning of the file:
import { useNavigate, useParams } from 'react-router-dom'
Next we have handlers for input fields. And after them we need to correct the function onSaveProductClick
. Now in it, when clicked, we will send the action productUpdated
with the received id and changed data as an object. After that, we will add our navigate
, to go to the page of the changed product:
const onSaveProductClick = () => {
if (name && desc && price && amount) {
dispatch(
productUpdated({
id: productId,
name,
desc,
price,
amount,
})
)
navigate(`/products/${productId}`)
}
}
All that remains is to find the line in our returned layout:
<h2>Add a New Product</h2>
And replace it with:
<h2>Edit Product</h2>
Open your application with students. Create a file EditStudentForm.jsx
similar to NewStudentForm.jsx
. Make changes to it as shown in the lesson.