1

I want to submit a form into mongoDB using nodejs API & reactJs. With the exception of the multiple select option, everything is operating as it should be.

Being new to react, I have no idea how to handle the multi select option's onChange method.

Here is what I've tried:

import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { v4 as uuidv4 } from 'uuid';
import axios from "axios";
import Select from 'react-select';

export default function EventForm(props) {

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm();
  const form = useRef();
  const [loading, setLoading] = useState(false);

  const [info, setInfo] = useState("");
  const [analysis, setAnalysis] = useState("Undefined");
  const [relatedEvent, setRelatedEvent] = useState([]);


  const handleInfoChange = (e) => {
    setInfo(e.target.value)
  }
  const handleAnalysisChange = (e) => {
    setAnalysis(e.target.value)
  }

  const handleRelatedEvents = (e) => {
    setRelatedEvent(e.target.value)
  }

  const relatedEventsData = props.data.map(opt => ({ label: opt.info, value: opt._id }));

  const onSubmit = async () => {
    setLoading(true);
    const MySwal = withReactContent(Swal);

    const eventData = {
      UUID: uuidv4(),
      info: info,
      analysis: analysis,
      relatedEvent: relatedEvent,
    }

    axios
      .post(`${process.env.REACT_APP_PROXY}/api/events`, eventData)
      .then((res) => {
        console.log(res);
        setLoading(false);
        MySwal.fire(
          "Success!",
          "A new event has been saved successfully",
          "success"
        );
      })
      .catch((error) => {
        console.log(error);
      });
    
  };

  return (
    <div className="panel-body">
      <Form
        ref={form}
        onSubmit={handleSubmit(onSubmit)}
        className="form-horizontal"
      >
        <div className="row">
          <div className="col-lg-6">
            <div className="mb-3">
              <Form.Label>Info</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter info..."
                {...register("info", { required: true })}
                value={info}
                onChange={handleInfoChange}
              />
              {errors.info && (
                <ul className="parsley-errors-list filled" id="parsley-id-7" aria-hidden="false">
                  <li className="parsley-required">This value is required.</li>
                </ul>
              )}
            </div>
           
          </div>
          
          <div className="col-lg-6">
            <div className="mb-3">
              <Form.Label>Related events</Form.Label>
              <Select
                options={relatedEventsData}
                value={relatedEvent}
                isMulti
                onChange={handleRelatedEvents}
              />

            </div>
          </div>
         
          <div className="col-lg-12">
            <Button variant="primary" type="submit">
              {loading ? "Saving..." : "Save"}
            </Button>
          </div>
        </div>
      </Form>
    </div>
  );
}

Could you please guide me how to make it work! Thank you

5
  • try setting the state as ... setRelatedEvent([...relatedEvent, e.target.value]) Commented Dec 5, 2022 at 12:31
  • I did try it but when I select an option from the option list it don't select any value! Commented Dec 5, 2022 at 12:35
  • I think the problem is in the <Select /> Commented Dec 5, 2022 at 12:36
  • because when I remove value={relatedEvent} and onChange={handlerelatedEvents} the select option works Commented Dec 5, 2022 at 12:37
  • sorry that won't work and need extra code to handle the removal of options .... try the below answer Commented Dec 5, 2022 at 12:44

1 Answer 1

1

you can make use of Select onChange event handler which passes the selected options as an array as argument ..

from that you can map over it to get the values as required something as below:

  const handleChange = (opts) => {
    const selectedValues = opts.map((opt) => opt.value);
    setSelectedValues(selectedValues);
  };

Please check the working sample for better clarity 😉 - Edit codesandboxer-example (forked)

Sign up to request clarification or add additional context in comments.

1 Comment

Did you do same as above ? and while submitting you can submit the selected ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.