Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
pass data from multiple checkbox to api only when a submit button is clicked :react js

pass data from multiple check box to api only when a submit button is clicked

i am having this accordions in my website when i click on check box all checkbox values get stored in state and at last when i click submit only the data is passesd to api the data stored are given bellow

   const getAccordionItem = ({ key, label }) => {
    const source = key === "Custom" ? "custom" : "items";

    return (
      <div className="accordion-item" key={key}>
        <div
          className="accordion-title gradiantblur"
          onClick={() => navClose(key)}
        >
          {/* // onClick={setActiveCurrentIndex(item[0].date)}> */}
          <div>{label}</div>
          <i className="fa fa-plus" aria-hidden="true"></i>
        </div>
        {state[key] ? (
          <div className="accordion-content  tableforsymtm">
            {(source !== "custom"
              ? state[source].filter(
                  (item) => item.category === label || item.category === key
                )
              : state[source]
            ).map((item, index) => {
              return (
                <span
                  key={`${key}__${item.id}__${index}`}
                  className="trforsymtm"
                >
                  <td>
                    <input
                      // className="invinsiveinput"
                      data-id={item.id}
                      type="checkbox"
                      id={item.id}
                      checked={item && item.positive}
                      onChange={(e) => handleCheckboxChange(e, source, item.id)}
                    />
                  </td>
                  <td className="tdoneline">
                    <label htmlFor={item.id}>{item.name}</label>
                  </td>
                </span>
              );
            })}
          </div>
        ) : null}
      </div>
    );
  };

  const handleCheckboxChange = (e, stateKey, itemId) => {
    const stateItems = state[stateKey];
    const index = stateItems.findIndex((item) => item.id === itemId);

    setState((prevState) => ({
      ...prevState,
      [stateKey]: [
        ...stateItems.slice(0, index),
        {
          ...stateItems[index],
          positive: e.target.checked,
        },
        ...stateItems.slice(index + 1),
      ],
    }));
  };

submit onbutton click

 const chekbox = (e) => {
    e.preventDefault();
    const headers = {

     
    };
    const data = {
      items: [...state.items]
        .filter((item) => item.positive)
        .map((item) => ({
          date: state.today,
          symptom: item.id,
          positive: item.positive,
        })),
    };

    const custum = {
      items: [...state.custom]
        .filter((item) => item.positive)
        .map((item) => ({
          date: state.today,
          symptom: item.id,
          positive: item.positive,
        })),
    };
    console.log(custum);
    axios.post("/customer/submit-multiple/", data, {
      headers: headers,
    });
    axios
      .post("/customer/submit-custom-multiple/", custum, {
        headers: headers,
      })
      .then(() => {
        alert("was submitted");
        window.location.reload();
      })
      .catch((error) => {
        alert("Cannot add submittedagain");
      });
  };


full code i have added in code sandbox note updated acccouding to Hirens answswer https://codesandbox.io/s/objective-jone5tlds

the issue now i am facing is that if a user clicks a check box its check value is added to state and if the user unchecks the check box before submiting there will be 2 entry in the array

  • one as checked (true)
  • 2nd as uncheked (false)

so checkbox data 2values cannot be submitted to array and passed to api

i want data to be passed something like this

i am getting 500 error

[
    {
        "date" : "2022-02-15",
        "id" : 6,
        "positive" : true
    },
    {
        "date" : "2022-02-15",
        "id" : 5,
        "positive" : true
    },
    {
        "date" : "2022-02-15",
        "id" :7,
        "positive" : true
    },
    {
        "date" : "2022-02-15",
        "id" : 11,
        "positive" : true
    },
    {
        "date" : "2022-02-15",
        "id" : 4,
        "positive" : true
    }
]
over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda