Gianluca
Gianluca

Reputation: 990

passing parameters to function react failing

I have this. this is my whole page, to avoid any confusion.

 import React, { useState, useEffect } from "react";
import axios from "axios";

const TourPage = () => {
  const [myData, setMyData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [showEditButton, setShowEditButton] = useState(false);

  useEffect(() => {
    axios
      .get("/getResults")
      .then((res) => {
        setMyData(res.data);
        setIsLoading(true);
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  const deleteById = (id) => {
    console.log(id);
    axios
      .post(`/deleteDoc`, { id: id })
      .then(() => {
        console.log(id, " worked");
        window.location = "/tour";
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      });
  };

  const editById = (id, siteLocation, Services, cnum) => {
    console.log(id, siteLocation, Services, cnum);
    axios
      .post(
        `/editDoc`,
        JSON.stringify({
          id: id,
          location: siteLocation,
          Services: Services,
          cnum: cnum
        }),
        {
          headers: {
            "Content-Type": "Application/json"
          }
        }
      )
      .then(() => {
        console.log(id, " worked");
        window.location = "/tour";
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      });
  };

  const onClickEdit = (e, _id) => {
    e.preventDefault();
    var siteLocation = document.getElementById("location").value;
    var Services = document.getElementById("Services").value;
    var cnum = document.getElementById("cnum").value;
    console.log(siteLocation, Services, cnum)
    editById(_id, siteLocation, Services, cnum);
  };

  const onTyping = (value) => {
    if (value.length > 0) {
      setShowEditButton(true);
    } else {
      setShowEditButton(false);
    }
  };

  return (
    <table id="customers">
      <tr>
        <th>siteLocation</th>
        <th>Services</th>
        <th>cnum</th>
      </tr>
      {myData.length > 0 &&
        myData.map(({ location, Services, cnum, _id }, index) => (
          <tr key={index}>
            <td>
              <input
                type="text"
                placeholder={location}
                onChange={(e) => onTyping(e.target.value)}
                name="location"
                id="location"
              />{" "}
            </td>
            <td>
              <input
                type="text"
                placeholder={Services}
                name="Services"
                id="Services"
              />{" "}
            </td>
            <td>
              <input
                type="text"
                placeholder={cnum}
                name="cnumhide"
                id="cnumhide"
              />{" "}
            </td>
            <td>
              <input type="hidden" placeholder={cnum} name="cnum" id="cnum" />{" "}
            </td>
            <button
              onClick={(e) => {
                e.preventDefault();
                deleteById(_id);
              }}
              disabled={isLoading}
            >
              Delete
            </button>
            {showEditButton && (
              <button onClick={(e) => onClickEdit(e, _id)}>Submit Edit</button>
            )}
          </tr>
        ))}
      {myData.length === 0 && "No Data Found"}
    </table>
  );
};

export default TourPage;

my problem is, when I click the submit edit button, none of the parameters get passed through to the backend, or to the editById function. I want to be able to grab the value of the parameters and update them in mongodb through backend. how do I fix this? I tried other things, but I think the document.getElementById may not be working. it could be the problem, but even so, I don't know where or how to fix. thanks

Upvotes: 0

Views: 44

Answers (1)

Sinan Yaman
Sinan Yaman

Reputation: 5946

If you must use html reference: (Not advised)

Seems like you can't get values from getElementById. It is an anti-pattern to use DOM manipulation inside a react app. Instead, use useRef hook if you must

Example:

import {useRef} from 'react'

const TourPage = () => {
  ...
  const cnumRef = useRef()
  const servicesRef = useRef()
  const siteLocationRef = useRef()
  ...

  const onClickEdit = (e, _id) => {
    e.preventDefault();
    var siteLocation = siteLocationRef.current;
    var Services = servicesRef.current;
    var cnum = cnumRef.current;
    console.log(siteLocation, Services, cnum)
    editById(_id, siteLocation, Services, cnum);
  };
  
  /* passing them to the html */
  return (
    ...
    <input
      ref={Services.ref}
      type="text"
      placeholder={Services}
      name="Services"
      id="Services"
    />
  )

}

Suggestions

Although refs will work in this case, I will strongly suggest using useState and creating seperate state variables for each of the inputs. useRef doesn't re-render if the value changes, therefore I would instead do:

import {useState} from 'react'

/* inside component: */
const [fields, setFields] = useState({
  cnum: "",
  services: "",
  ...
})

const handleInputChange = e => setFields(f => ({...f, [e.target.name]: e.target.value}))

return (
    ...
    <input
      ref={Services.ref}
      type="text"
      value={fields.services}
      onChange={handleInputChange}
      placeholder={Services}
      name="services"
      id="Services"
    />
  )

Upvotes: 2

Related Questions