samedi 18 avril 2020

How can I pass checkbox data made using React Hook Form to my database?

I have a form with a checkbox where I would like users to tick one or more than one box for animals tags. I would like the one they have tagged to be added into my DB, for example "Lion" into my tags field. The rest of the form seems to be working fine but the checkbox seems tricky.

My client side form - with checkboxes

import React, { useState, useEffect } from "react";
import {
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  FormGroup,
  Label
} from "reactstrap";
import { useForm } from "react-hook-form";
import axios from "axios";
import LogRocket from "logrocket";

const addProj = {
  textAlign: "center",
  margin: "0",
  position: "relative",
  top: "50%",
  left: "35%",
  width: "30%",
  height: "50px"
};

const NewProject = () => {
  // Toggles modal
  const [modal, setModal] = useState(false);
  const toggle = () => setModal(!modal);

  // State for form and contents
  const [loading, setLoading] = React.useState(true);
  const { handleSubmit, register, errors } = useForm();
  const [items, setItems] = React.useState([
    { label: "Loading", value: "Loading" }
  ]);

  // Runs on form submission
  const onSubmit = values => {
    axios.post("http://localhost:3000/api/addProject", values);
    toggle();
  };

  useEffect(() => {
    // initialised as false
    let unmounted = false;
    async function getUsers() {
      axios
        .get("http://localhost:3000/api/Users/findUser")
        .then(res => {
          if (!unmounted) {
            setItems(
              res.data.map(({ name, _id }) => ({
                label: name,
                value: _id
              }))
            );
            setLoading(false);
            // setLoading allows change to option - data displayed
          }
        })
        .catch(error => LogRocket.captureException(error));
    }
    // controls dropdown feature after obtaining values
    getUsers();
    return () => {
      unmounted = true;
    };
  }, []);

  return (
    <div>
      <Button style={addProj} outline color="primary" onClick={toggle}>
        Add New Project
      </Button>
      <Modal isOpen={modal} toggle={toggle}>
        <ModalHeader toggle={toggle}>Add New Project</ModalHeader>
        <ModalBody>
          <form onSubmit={handleSubmit(onSubmit)}>
            <FormGroup>
              <Label for="name">Project Name: </Label>
              <br></br>
              <input
                type="text"
                placeholder="ProjectName"
                name="name"
                ref={register({ required: true, maxLength: 20 })}
              />
              {errors.name && " Project name is required"}
            </FormGroup>
            <FormGroup>
              <Label for="type">Project Type: </Label>
              <br></br>
              <input
                type="text"
                placeholder="Project Type"
                name="type"
                ref={register({ required: true, maxLength: 20 })}
              />
              {errors.details && " Project type is required"}
            </FormGroup>
            <FormGroup>
              <Label for="details">Project Detail ( max 20 characters): </Label>
              <br></br>
              <input
                type="text"
                placeholder="Project Details"
                name="details"
                ref={register({ required: true, maxLength: 20 })}
              />
              {errors.details && " Project detail did not meet the requirement"}
            </FormGroup>
            <FormGroup>
              <Label for="details">Project Description: </Label>
              <br></br>
              <input
                type="text"
                placeholder="Project Details"
                name="description"
                ref={register({ required: true, maxLength: 140 })}
              />
              {errors.details && " Project details are required"}
            </FormGroup>
            <FormGroup>
              <Label for="users">Add User/Users </Label>
              <br></br>
              <select
                name="users"
                disabled={loading}
                ref={register({ required: true })}
                multiple
              >
                {items.map(({ label, value }) => (
                  <option key={value} value={value}>
                    {label}
                  </option>
                ))}
              </select>
              {errors.users && " Please select a user"}
            </FormGroup>
            <FormGroup>
              <Label for="tags">Project Tags: </Label>
              <br></br>
              <Label for="tag">Lion </Label>
              <input type="checkbox" name="tags" value="Lion" />
              <br></br>
              <Label for="tag">Elephant </Label>
              <input type="checkbox" name="tags" value="Elephant" />
              <br></br>
              <Label for="tag">Tiger </Label>
              <input type="checkbox" name="tags" value="Tiger" />
            </FormGroup>
          </form>
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={handleSubmit(onSubmit)}>
            Add New Project
          </Button>
          <Button color="secondary" onClick={toggle}>
            Cancel
          </Button>
        </ModalFooter>
        <ModalFooter>
          <p>{Error}</p>
        </ModalFooter>
      </Modal>
    </div>
  );
};

export default NewProject;

My Server side API route

const express = require("express");
const addProject = express.Router();
const ProjectModel = require("../../../models/Project");

// add project
addProject.post("/addProject", async (req, res) => {
    // handle users addition
    let { users = [] } = req.body;
    users = users.map(value => ({ userId: value }));
    console.log(users);
    let newProject = new ProjectModel({
        name: req.body.name,
        type: req.body.type,
        users,
        details: req.body.details,
        description: req.body.description,
        tags: req.body.tags

    });

    newProject.save(function(error, newProject) {
        if (error) {
            res.send(error);
        } else {
            res.send(newProject);
        }
    });
});

module.exports = addProject;



Aucun commentaire:

Enregistrer un commentaire