在ReactJS中使用useFormik时如何使用uuid作为item ID?

问题描述 投票:0回答:1

我使用 useForm 在 ReactJS 中提交表单。 在 useForm 中,我们定义了带有空白内容的初始值。

对于输入,我们使用值,例如: 值={formik.values.bookName}

我想为自动提交的id分配uuid,其他字段(例如bookname和autherName)使用输入值提交。 但我不知道何时以及如何分配它。

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
reactjs uuid formik yup
1个回答
0
投票
onSubmit: (values) => {
  const id = uuid(); // Generate UUID here
  const updatedValues = { ...values, bookId: id }; field
  setValueArray([...valueArray, updatedValues]);
  formik.resetForm();
© www.soinside.com 2019 - 2024. All rights reserved.