简体   繁体   中英

Post Conditional Data in ReactJs

so I want to add conditional statements in my POST method function in React. I have a useState variable called empType that could be toggled by buttons to be set to "normal" or "others". I want to be able to exclude data2 from the JSON data that will be posted if empType is set to normal. I tried using {empType:== "normal" && data2: "something"} but obviously its a syntax error.

Here is my code

export default function App() {
  const [empType, setEmpType] = useState("blank");
  const onSubmit = () => {
    fetch(`/apiendpoint`, {
      method: "POST",
      headers: { "Content-type": "application/json; charset=UTF-8" },
      body: JSON.stringify({
        data1: "something",
        data2: "something"
      })
    })
      .then((response) => response.json())
      .then((message) => console.log(message))
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <div className="App">
      <button onClick={() => setEmpType("normal")}>
        set Emp type to normal
      </button>
      <br />
      <button onClick={() => setEmpType("others")}>
        set Emp type to others
      </button>
      <br />
      Emp Type = {empType}
      <br />
      <button onClick={onSubmit}>submit</button>
    </div>
  );
}

I highly appreciate any help. Thank you

why not try building the data before the fetch call.

const onSubmit = () => {
  const data = {
    data1: "something"
  }

  if (empType !== "normal") data.data2 = "something"

  fetch(`/apiendpoint`, {
    method: "POST",
    headers: { "Content-type": "application/json; charset=UTF-8" },
    body: JSON.stringify(data)
  })
   .then((response) => response.json())
   .then((message) => console.log(message))
   .catch((error) => {
     console.log(error);
   });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM