Home > OS >  how to send a user onClick event to different endpoint urls based on the button clicked using ReactJ
how to send a user onClick event to different endpoint urls based on the button clicked using ReactJ

Time:10-28

I am using react hooks with axios, react-boostrap and i have two buttons on the same page, they are part of the same form because they are supposed to send the fields...

what i am trying to achieve is send the user to different endpoint url based on the button clicked on the front end.

Currently the onSubmit/onClick event its not doing anything, meaning the event is not being triggered at all, i tried the codes below and also to add buttonURLState as a parameter to the handleSubmit function (it failed first on the type then i passed buttonURLState: void) but still nothing is being triggered.

form.tsx

const [buttonState, setButtonState] = useState("");

...

let buttonURLState: any = null;

  if (buttonState === "sendToURL1") {
    buttonURLState = "someURL1"; 
  }

  if (buttonState === "sendToURL2") {
    buttonURLState = "someURL2"; 
  }

 const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault();

      axios.post(`http: //www.foo.com/${buttonURLState}/`, data, options)
      .then(response => {
        ...
  }

return
  ....
   <Form onSubmit={handleSubmit}>
      <Form.Label>Name</Form.Label>
         <Form.Group role="form" controlId="name">
           <Form.Control
             autoFocus
             required
             size="lg"
             className="submit-button-text"
             type="text"
             name="name"
             value={fields.name}
             onChange={handleFieldChange}
          />
          ...
          <div>
            <div>
             <Button size="lg" variant="secondary" onClick={() => setButtonState("sendToURL1")}>Send Me to URL1</Button>
            </div>
            <div>
             <Button size="lg" variant="primary" onClick={() => setButtonState("sendToURL2")}>Send Me to URL2</Button>
            </div>
           </div> 
          </Form>

...

PS: do not mind about the space in the endpoint URL above, its a way to be able to post the question to this website

is there something that i am doing wrong, any help to send to different urls endpoints would be much appreciated

CodePudding user response:

You may not need the form tag here at all. Just call a completely separate function from each button:

const goToUrl1 = async () => {
  const res = await axios.post('foo.com/url1/', { name: fields.name })
  console.log(res.data)
}

const goToUrl2 = async () => {
  const res = await axios.post('foo.com/url2/', { name: fields.name })
  console.log(res.data)
}

<div>
  <Button onClick={() => goToUrl1()}>Send Me to URL1</Button>
</div>
<div>
  <Button onClick={() => goToUrl2()}>Send Me to URL2</Button>
</div>
  • Related