Home > OS >  Post Conditional Data in ReactJs
Post Conditional Data in ReactJs

Time:05-04

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

CodePudding user response:

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);
   });
};
  • Related