The auth component as middleware in

How can I provide access only to a registered user in order to have access to the home page and the task page? I use redux and I try to avoid any ready-made auth component in order to learn more about auth.

const App = props => (
    <BrowserRouter>
        <Provider store={store}>
            <div className="app">
                <Layout>
                <Header>
                    <Navbar />
                </Header>
                <Content>
                    <Route exact path='/' component={Home} />
                    <Route exact path='/login' component={Login} />
                    <Route exact path='/signup' component={Signup} />
                    <Route exact path='/task/:id' component={Task} />
                </Content>
                </Layout>
            </div>
        </Provider>
    </BrowserRouter>
)

I used angular and there was an intermediate concept in the route, but in response I get lost. I think auth has nothing to do with redux store? Do I need to call to get detailed user information from the api when the user moves around the application?

+4
source share
1 answer

, . , , "", .

"" . Redux connect HOC. . , , localStorage .. :

import React from 'react'

export default function(ComposedComponent) {

  class RequireAuth extends Component {

    state = {
      isAuthenticated: false
    }

    // Push to login route if not authenticated on mount
    componentWillMount() {
      if(!this.state.authenticated) {
        // Use your router to redirect them to login page
      }
    }

    // Push to login route if not authenticated on update
    componentWillUpdate(nextProps) {
      if(!this.state.authenticated) {
        // Use your router to redirect them to login page
      }
    }

    // Otherwise render the original component
    render() {
      return <ComposedComponent {...this.props}/>
    }

  }

  return RequireAuth

}

HOC RequireAuth - , :

<Route exact path='/' component={RequireAuth(Home)} />

: , RequireAuth, . RequireAuth isAuthenticated true. , - . connect HOC , isAuthenticated .

0

Source: https://habr.com/ru/post/1684561/


All Articles