score:2

Accepted answer

you don't need to use the link component in this example. try using the history prop (props.history.push('/')) see the below examples, the last one should apply to you:

in your app.js router:

<switch>
  <route path="/auth" component={auth} />
  <route path="/errorpage" component={errorpage} />
  <route path="/" exact component={homescreen} />
  <redirect to='/' />
</switch>

on the page where you want to redirect:

import react, { usestate } from 'react'

const auth = props => {

    const [form, setform] = usestate({
        data: {
            email: '',
            password: ''
        }
    })

    const authhandler = async (event) => {
        event.preventdefault()
        try {
            // await dispatch(action) // dispatch to redux or send a fetch
            props.history.push('/')  // redirects if no errors
        } catch (err) {
            props.history.push('/errorpage')  // redirects if an error
        }
    }

    const inputchangedhandler = e => {
        setform({
            ...form,
            data: {
                ...form.data,
                [e.target.id]: e.target.value
            }
        })
    }

    return (
        <div>
            <form onsubmit={authhandler}>
                <input id='email' type='email' value={form.data.email} onchange={inputchangedhandler} />
                <input id='password' type='password' value={form.data.password} onchange={inputchangedhandler} />
                <button type='submit'>login</button>
            </form>
        </div>
    )
}

export default auth

in your case try the below if the page is on the route stack the history prop will be available or you will have to use withrouter or usehistory hook to get access to the history prop.

const clickhandler = () => {
     try {
         // await dispatch(action)
         props.history.push('/')  // redirects
     } catch (err) {
         props.history.push('/errorpage')  // redirects
     }
}

return (<button type='button' onclick={clickhandler}>click me</button)

score:0

you can use "redirect" from "react-router-dom"

example:

    import { redirect } from "react-router-dom";

    <link to='/upload'>
          <button
          variant="contained"
          color="primary"
          onclick={async () => {
            await verificationp(phone, code).then(async (result) => {
              if ((await result) === true) {
                //i want to redirect to another page

                return <redirect to="your_url" />

              } else {
                //i want to display an alert
              }
            });
          }}
        >
          submit
        </button>
    </link>

score:0

i tend to use the state system (redux) to resolve this issue.

so my problem was i wanted to fire an event.preventdefault() to stop a link being clicked, but then i wanted to do an api call after it (to check login status, as it was a complex iot device) and click the link if the check was fine, but not click the link if it wasn't. however, the event.preventdefault() stopped me doing this, because it cancels any events (i'm sure there are nicer ways to achieve this! but time targets and all that).

i solved this by:

  1. having my usual async function with the event.preventdefault() inside it.
  2. within the first call i set some state in redux, just a basic boolean.
  3. if the api check was successful then i call the same click function again (using .click()) and bypass the event.preventdefault() thanks to redux (then reset the state afterwards) which forces the re-direct. if the check failed then i display an error message and don't display again (while obviously updating redux).

the state management system inside react is very powerful. you can do some hacky things! but sometimes the other "correct" solutions don't work for you; for example the history props functionality, which you can get round that other ways via state management.

score:2

here is the redirect doc

i think best thing you can do is create a separate function for onclick and change a state to redirect, so this way you can prevent some action by user while request is in progress

const [redirectto, setredirectto] = usestate('');

const chekcfromserver = async () => {
  await verificationp(phone, code).then(async (result) => {
    if ((await result) === true) {
      setredirectto('/somewhereinyour/application')
    } else {
      // i want to display an alert
    }
  });
};

and when in render

return (
    <>
        redirectto && <redirect to={{pathname: redirectto }} />
       ...rest of your code
    </>
)

Related Query

More Query from same tag