How to parseint a combined POSTed object data types

Viewed 22

I have a combined data types POSTed to API. I would like to parseInt() some of theses data (Price, vat, status, company_id). Trying to POST the form gets me an Error :

POST https://api.factarni.tn/article/create 420

Also, in Console.dev-Network tab, it response with invalid data (that's why i need to parseInt specific strings like price, vat, status and company_id:

{
  "message": "Invalid data",
  "code": 400,
  "date": "2022-09-11T14:04:53.903Z",
  "level": "error"
}

My app is responding on console.dev-Network-payload with:

{
  "code": "",
  "article": "",
  "price": 0,
  "vat": 0,
  "status": 0,
  "company_id": 0,
  "Code": "code1",
  "Article": "article1",
  "Price": "10",
  "Vat": "20",
  "Status": "30",
  "Company_id": "40"
}

You can notice that application trying to send the initial states of useState AND the entred values in form. How to make my application send only inputed form values and parsingInt the Price, vat, status and company_id values?

My code:

const New = ({ inputs, title }) => {
  const [data, setData] = useState({
    code: "",
    article: "",
    price: 0,
    vat: 0,
    status: 0,
    company_id: 0,
  });

  function handle(e) {
    const newdata = { ...data };
    newdata[e.target.id] = e.target.value;
    setData(newdata);
    console.log(newdata);
  }

  const handleClick = async (e) => {
    e.preventDefault();

    await fetch("https://api.factarni.tn/article/create", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
        Authorization:
          "Bearer eyJhbGciOiJSUzI...qw2QWltkyA",
      },
    });
  };

  return (
    <div className="New">
          //...
            <form>
              //...
              {inputs.map((input) => (
                <div className="formInput" key={input.id}>
                  <label>{input.label} </label>
                  <input
                    type={input.type}
                    placeholder={input.placeholder}
                    onChange={(e) => handle(e)}
                    id={input.label}
                    value={data.form}
                    name="data"
                  />
                </div>
              ))}
              <button onClick={handleClick}>Add</button>
            </form>
          //...
    </div>
  );
};
0 Answers
Related