Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Auth state and Routes . Failed to execute 'replaceState' on 'History' inside React-Router

Using packages

  "react-router": "^4.3.1",
   "react-router-dom": "^4.3.1",

App.js

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      authState: null,
    };
  }

  mutateAuthState = () => {
    this.setState({
       authState: true,
      });
  }
  render() {
    return (<Routes authState={this.state.authState}  mutateAuthState={this.mutateAuthState} />)
    }
}

Routes.js

class Routes extends React.Component {
    render() {
      return (
        <React.Fragment>

            <BrowserRouter >
              <Switch>
                  <Route path="/login" exact render={  () => <Login authState={this.props.authState} 
                                                                    mutateAuthState={this.props.mutateAuthState}/>
                                                     } /> 
                  <Route path="/" exact render={  () => <div><a href="/login" >login</a></div> } />
            </Switch>
      </BrowserRouter>
  </React.Fragment>
      );
    }
  }

Login.js

class Login extends Component {


  handleSubmit = async (event) => {

     this.props.mutateAuthState(true)

 }

  render() {

    switch(this.props.authState) {
      case true : return (<Redirect to="\" />)

       default :    return(
      <button onClick={this.handleSubmit}  >Login </button>

    )
  }
}
}

End result wanted - Clicking Login Button in Login.js will set the state variable authState in App.js to true.

App will rerender Routes.js since state has changed.

Inside Routes, since the url is still /login , Login component is rendered.

Inside Login, since this.props.authState is now set to true, a redirect to "/" occures.

But I am getting a DOMException in Web Console

Error: DOMException: Failed to execute 'replaceState' on 'History': A history state object with URL 'http:' cannot be created in a document with origin 'http://localhost:3000' and URL 'http://localhost:3000/login'.

enter image description here

Is this the proper architecture for Authentication in React?

like image 418
Shorn Jacob Avatar asked Oct 25 '18 03:10

Shorn Jacob


1 Answers

Two things that I can see.

Shouldn't you be redirecting to forward slash and not backslash?

aka change <Redirect to="\" /> to <Redirect to="/" />

Second thing is you probably need to upgrade your version of react-router. The issue is your redirect is trying to go back to home, but there is a bug when redirecting to the / route.

Version 4.6.1 should correctly redirect for you.

like image 147
John Ruddell Avatar answered Oct 23 '22 09:10

John Ruddell