skip to Main Content

I use useForm for submit my form in ReactJS.
In useForm we define initialValues whith blank content.

and for inputs we use values for example:
value={formik.values.bookName}

I want to assign for id uuid that submit automatically, and other field such as bookname and autherName submit with input values.
But I do not when and how to assign that.

import React, { useState, useEffect } from 'react';
import { useFormik } from "formik";
import * as Yup from "yup";
import { Table, Button, Row, Col } from 'react-bootstrap';
import { v4 as uuid } from "uuid";


const getDataFromLs = () => {
    const data = localStorage.getItem('valueArray');
    if (data) {
        return JSON.parse(data)
    } else {
        return [];
    }
}

const formSchema = Yup.object({
    bookName:
        Yup.string()
            .required("لطفا نام کتاب را وارد نمایید")
            .min(3, "نام کتاب کمتر از 3 حرف نباشد"),

    autherName:
        Yup.string().required().min(4).max(10),

})

const FormikYupAddBook = () => {


    const [valueArray, setValueArray] = useState(getDataFromLs)
    const [id, setId] = useState('')

    useEffect(() => {
        localStorage.setItem('valueArray', JSON.stringify(valueArray))
        console.log('dddd', valueArray)
    }, [valueArray])

    const formik = useFormik({
        initialValues: {
            bookId: "",
            bookName: "",
            autherName: "",
        },
        validationSchema: formSchema,


        onSubmit(values) {
            
            localStorage.setItem('values', JSON.stringify(formik.values))

            setValueArray([...valueArray, values])
            console.log('vvvvv', valueArray);
        }


    })

    return (
        <div>
            <div style={{ width: "600px" }}>
                <form action="/action_page.php">
                    <div class="input-group">

                        <div class="input-group-btn">
                            <button style={{ height: "40px", width: "100px", backgroundColor: "blue" }} class="btn btn-default text-white" type="submit">submit<i class="glyphicon glyphicon-search"></i></button>
                        </div>
                        <input style={{ direction: "rtl" }} type="text" class="form-control" placeholder="Search" name="search" />
                    </div>
                </form>

            </div>
            <Row>
                <Col md={1} style={{ backgroundColor: 'pink' }}>
                    blue
                </Col>


                <Col md={6} style={{ backgroundColor: 'white' }}>
                    <input class="form-control form-control-lg" type="text" placeholder=".form-control-lg" />



                    <Table striped bordered hover>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>نام کتاب</th>
                                <th>نام نویسنده </th>

                            </tr>
                        </thead>
                        <tbody>
                            {

                                valueArray.map((book) =>


                                    <tr>
                                        <td>{book.bookId}</td>
                                        <td>{book.bookName}</td>
                                        <td>{book.autherName}</td>

                                    </tr>

                                )

                            }

                        </tbody>
                    </Table>

                </Col>



                <Col md={4} >
                    <div style={{
                        backgroundColor: "#E7E9EB !important",
                        color: "black !important", padding: "8px 16px !important",
                        border: "1px solid #ccc !important",
                        borderRadius: "5px"
                    }} class="container-fluid mt-3 w3-border w3-padding w3-round ws-grey" >
                        <form action="/action_page.php">
                            <div class="mb-3 mt-3">
                                <label for="email" class="form-label">Email:</label>
                                <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" />
                            </div>
                            <div class="mb-3">
                                <label for="pwd" class="form-label">Password:</label>
                                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd" />
                            </div>
                            <div class="form-check mb-3">
                                <label class="form-check-label">
                                    <input class="form-check-input" type="checkbox" name="remember" /> Remember me
                                </label>
                            </div>
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </form>
                    </div>




                    <form onSubmit={formik.handleSubmit}>
                        <div>


                            <input

                                name="bookId"

                                value={formik.values.bookId}
                                onChange={() => {setId(uuid())}}

                            />
                            <input
                                style={{ fontSize: "10px", width: "300px", height: "40px", direction: "rtl" }}
                                className="form-control"
                                name="bookName"
                                placeholder="لطفا نام کتاب را وارد نمایید."
                                value={formik.values.bookName}
                                onChange={formik.handleChange}
                                onBlur={formik.bookName}
                            />
                            {formik.submitCount > 0 && formik.errors.bookName && (
                                <p>{formik.errors.bookName}</p>
                            )}
                        </div>
                        <div>
                            <input
                                style={{ fontSize: "10px", width: "300px", height: "40px", direction: "rtl" }}
                                name="autherName"
                                placeholder="لطفا نام نویسنده را وارد نمایید."
                                value={formik.values.autherName}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                            />
                            {formik.submitCount > 0 && formik.errors.autherName && (
                                <p>{formik.errors.autherName}</p>
                            )}
                        </div>

                        <button >Submit</button>
                    </form>


                </Col>

                <Col md={1} style={{
                    backgroundColor: 'purple',
                }}>


                </Col>
            </Row>

        </div >
    )
}

export default FormikYupAddBook

2

Answers


  1. onSubmit: (values) => {
      const id = uuid(); // Generate UUID here
      const updatedValues = { ...values, bookId: id }; field
      setValueArray([...valueArray, updatedValues]);
      formik.resetForm();
    
    Login or Signup to reply.
  2. Try this in your code :

    const [valueArray, setValueArray] = useState(getDataFromLs);
    
        const formik = useFormik({
            initialValues: {
                bookId: "", 
                bookName: "",
                autherName: "",
            },
            validationSchema: formSchema,
            onSubmit(values, { resetForm }) {
                const newBook = {
                    ...values,
                    bookId: uuid(), // Assigning UUID to bookId when the form is submitted
                };
    
                setValueArray([...valueArray, newBook]);
                resetForm(); // Reset the form after submission
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search