React Hook useState returns undefined for props value but props value appears on textbox value

Viewed 867

So I have this code wherein the value of a textbox is from a prop. When i put the "props.completeAddress" directly to the textbox value, the value appears without a problem. But I have to make it editable. So I have a const[inputAddress, setInputAddress] and in the useState I put the props.completeAddress, then used "inputAddress" for the value of a textbox. Ideally the value should appear but it returns "undefined".

Photo for reference: what appears when i directly put "props.completeAddress" for the textbox value

       function BarangayInput(props) {
  const [inputAddress, setInputAddress] = useState(
    props.completeAddress
  );
  const [showList, setShowList] = useState(false);
  const [barangayList, setBarangayList] = useState([]);

  function onChange(e) {
    props.onChangeHandler(e, "barangay");
    getBarangayAPI();
  }

  helper.log("[Barangay Input]: render");
  helper.log("[Barangay Input]: render", barangayList);

  return (
    <div style={{ margin: "0" }} className={style.barangay}>
   
      <input
        style={{ width: "100%" }}
        className={style.inputstyle + " " + style.barangayinput}

        disabled={!props.isEditable}
        onChange={onChange}
        value={inputAddress}
        id={8}
        placeholder="Ex: Santolan, Pasig City, 1610"
        //value={props.partnerProfile.email_address}
      />
      {showList ? <div className={style.listContainer}>{list}</div> : null}
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    barangay: state.profileAndDetails.barangay,

    completeAddress:
      state.profileAndDetails.partnerProfileAndDetails.barangay +
      " " +
      state.profileAndDetails.partnerProfileAndDetails.city +
      " " +
      state.profileAndDetails.partnerProfileAndDetails.province +
      " " +
      state.profileAndDetails.partnerProfileAndDetails.zip_code,

    barangay: state.profileAndDetails.partnerProfileAndDetails.barangay,
  };
};
1 Answers

I see no issue other than the onChange handler isn't updating the local state.

function BarangayInput(props) {
  const [inputAddress, setInputAddress] = useState(props.completeAddress);
  
  ...

  function onChange(e) {
    props.onChangeHandler(e, "barangay");
    getBarangayAPI();
    setInputAddress(e.target.value); // <-- update state
  }

  ...

  return (
    <div style={{ margin: "0" }} className={style.barangay}>
      <input
        style={{ width: "100%" }}
        className={style.inputstyle + " " + style.barangayinput}
        disabled={!props.isEditable}
        onChange={onChange}
        value={inputAddress}
        id={8}
        placeholder="Ex: Santolan, Pasig City, 1610"
      />
      ...
    </div>
  );
}

Edit react-hook-usestate-returns-undefined-for-props-value-but-props-value-appears-on

Related