Skip to content
Advertisement

Updating the checkbox value based on the backend reponse using react

I’m trying to do an edit function, Where I’ll get the data from the backend. So if the value of dependents is ‘1,2’ then box the checkbox should be selected. I should be able to unselect the checkbox and send the value again if needed. In the below one, When we click on the add for the second row I’m checking if value of check box as 2 (line:79) and it’s showing as checked. The problem is when I’m unable to unselect it and send it again.

https://codesandbox.io/s/naughty-rhodes-i2sn9?file=/src/App.js

Advertisement

Answer

I have changed your code a bit, dependents state cannot handle dependents of all form values, so I have added a dependent object inside the form values object, I have tested it and it is working, Only the code and logic for checkbox is modified all other codes is similar to yours

https://codesandbox.io/s/react-fiddle-forked-ubcz4

try this

import React, { useState } from "react";

const App = () => {
  const [formValues, setFormValues] = useState([
    { orderno: 1, inputValue1: "", inputValue2: "", dependentParams: [] }
  ]);
  const [dependents, setDependents] = useState("");

  // control order number in a state to make sure
  // that it does not get messed when you remove
  // an indice from formValues
  // !! default was 0. so set it to 1
  const [orderNumber, setOrderNumber] = useState(1);

  const addFormFields = () => {
    let dependentString = [];
    formValues.map((d, i) => {
      dependentString.push(i + 1);
    });
    setFormValues((prevState) => [
      ...prevState,
      {
        orderno: orderNumber + 1,
        inputValue1: "",
        inputValue2: "",
        dependentParams: dependentString.length ? dependentString : []
      }
    ]);
    // increment order number
    setOrderNumber((prev) => prev + 1);
  };

  const removeFormFields = (i) => {
    let newFormValues = [...formValues];
    newFormValues.splice(i, 1);

    setFormValues(newFormValues);

    // decrement order number
    setOrderNumber((prev) => prev - 1);
  };

  const onChangeFieldValue = (index, key, value) => {
    setFormValues((prevState) => {
      let copyState = [...prevState];
      copyState[index][key] = value;
      return copyState;
    });
  };
  const onchangeCheckbox = (e, orderNo, index) => {
    setFormValues((prevState) => {
      let copyState = [...prevState];
      let dependentParams = [...copyState[orderNo].dependentParams];
      console.log(index, dependentParams);
      if (dependentParams.indexOf(index) !== -1) {
        dependentParams.splice(dependentParams.indexOf(index), 1);
      } else {
        dependentParams.push(index);
      }
      copyState[orderNo].dependentParams = dependentParams;
      return copyState;
    });
  };

  const saveFields = (e) => {
    const queryparam = {
      data: "xxx",
      DbData: "xxx",
      SQlData: "xxx", // only checked ones
      overallData: { formValues : formValues.map(d => ({...d, dependentParams:d.dependentParams.join(',')})) }
    };
    console.log(queryparam, "hhhhhhh");
  };

  const rows = (ele, orderno) => {
    let rowNos = [];
    for (let i = 0; i < orderno; i++) {
      rowNos.push(
        <>
          <input
            type="checkbox"
            value={orderno - i}
            id={orderno - i}
            checked={ele.dependentParams.indexOf(orderno - i) !== -1}
            onChange={(e) => {
              onchangeCheckbox(e, orderno, orderno - i);
            }}
          />
          Params {orderno - i}
        </>
      );
    }
    return rowNos;
  };
  return (
    <>
      {formValues.length <= 4
        ? formValues.map((element, index) => (
            <div className="form-inline" key={index}>
              <label>{index + 1}</label>

              <input
                type="text"
                value={element.inputVal1}
                onChange={(e) =>
                  onChangeFieldValue(index, "inputValue1", e.target.value)
                }
              />
              <input
                type="text"
                value={element.inputVal2}
                onChange={(e) =>
                  onChangeFieldValue(index, "inputValue2", e.target.value)
                }
              />
              {rows(element, index)}

              <button
                className="button add"
                type="button"
                onClick={() => addFormFields()}
              >
                Add
              </button>

              <button
                type="button"
                className="button remove"
                onClick={() => removeFormFields(index)}
              >
                Remove
              </button>
            </div>
          ))
        : ""}
      <button
        type="button"
        className="button remove"
        onClick={(e) => saveFields(e)}
      >
        Save
      </button>
      <button
        type="button"
        className="button remove"
        //onClick={(e) => cancelFields(e)}
      >
        cancel
      </button>
    </>
  );
};

export default App;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement