2

In my react app I am trying to redirect using props.history.push() on the click of a button but unfortunately, it isn't redirecting (yes, I checked if the path exists). This is the exact function that is getting triggered when the button is clicked.

If I put props.history.push() above await firebaseApp.signUp(username, email, password) then it works, but that doesn't make much sense, as I will be redirected even if I have errors.

const signup = async () => {
  try {
    await firebaseApp.signUp(username, email, password);
    props.history.push("/daily");
  } catch (error) {
    alert(error.message);
  }
};

This is the signUp function defined in firebaseApp class:

  async signUp(name, email, password){
    await this.auth.createUserWithEmailAndPassword(email, password)
    return this.auth.currentUser.updateProfile({
      displayName:name
    })

What is the solution to this problem?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Pranil
  • 21
  • 1

1 Answers1

0

I had the same issue a while back.

Here's how I fixed it -

history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

App.js

class App extends Component {
    render() {  
    return(
   <Router history={history}>
      <Router history={history}>
                <Switch>
                    <Route
                        path="/sign-up"
                        render={(props) => <SignUpForm {...props} />}
                    />

                    <PrivateRoute
                        exact
                        path={ROUTES.HOME}
                        component={Homepage}
                    />

                </Switch>
            </Router>
     );
   }
 }

SignUpForm.js

import history from "./Routes/history";

class SignUpForm extends React.Component {

    handleSignUp = (e) => {
  //Add your success logic here
                    history.push("/home");
                }
    render() {
        return (
            <form onSubmit={this.handleLogin}>
                <div className="form-submit">
                    <Button
                        variant="outline-success"
                        size="xs"
                        block
                        type="submit"
                    >
                      Submit
                    </Button>
                </div>
            </form>
        </div>
    </div>
  );
}
 }
theabrar
  • 360
  • 1
  • 6
  • 15
  • 1
    dont u think its just too much efforts for such a small thing cause the problem is that I have a lots of components in my app so I will have to pass history in props for every component in create..Is there any other way? @theabrar – Pranil Oct 23 '20 at 08:44
  • 1
    @Pranil you can look at a previous discussion on this topic - https://stackoverflow.com/a/42716055/14492980 – theabrar Oct 23 '20 at 09:29