How to convert null to empty String in Ionic React?

Issue

I want to submit a form in an API endpoint. I have many inputs, but here I’m including only the input which causes the error: ‘phone’ input, which is not required.
When I don’t fill ‘phone’ input, I get this error:

{validation_messages: {phone: {stringLengthInvalid: "Invalid type given. String expected"},…},…}
detail: "Failed Validation"
status: 422
title: "Unprocessable Entity"

In Backend, it accepts String or empty String ”.
Error:
{
"phone": null,
}
Correct:
{
"phone": ""
}

My component:

const UpdateData: React.FC = () => {
  const {
    phone,
    setPhone,
  } = React.useContext(MyContext);

  
  const updateContact = () => {
    const data = {
   
      phone: phone,
     
    };

    axios
      .put("/xx/update", data)
      .then((response) => {
        setPhone(response.data.phone);
        return response.data;
      })
      .catch((error) => {
        setMessage("Sth went wrong!");
        setIserror(true);
      });
  };

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
        <IonContent className="ion-padding">
          <IonGrid>
                <form className="ion-padding">
 
                  <IonItem>
                    <IonLabel position="floating">Phone</IonLabel>
                    <IonInput
                      placeholder="Example: 0333-12345678"
                      value={phone}
                      onIonChange={(e) => setPhone(e.detail.value)}
                    ></IonInput>
                  </IonItem>

                  <IonButton
                    className="ion-text-center btn-warning"
                    type="submit"
                    onClick={(e) => {
                      e.preventDefault();
                      updateContact();
                      history.goBack();
                    }}
                  >
                    Save
                  </IonButton>
                </form>
          </IonGrid>
        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default UpdateData;

In ‘MyContext’ I have set states for my input:

const [phone, setPhone] = useState<string>("");

Any help would be really appreciated.

Solution

you can try something like this:

const data = {
   
      phone: phone || "",
     
    };

Answered By – devrnd

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published