redux-auth-wrapper icon indicating copy to clipboard operation
redux-auth-wrapper copied to clipboard

Example for React Native

Open mjrussell opened this issue 8 years ago • 9 comments

#33 implements React Native support. React-router doesn't support native but there is a lot of good things being said about https://github.com/aksonov/react-native-router-flux.

Should create a basic React Native app, the auth wrappers should look almost identical except will need to override the redirectAction with a redux action.

mjrussell avatar Apr 26 '16 17:04 mjrussell

Trying to use with react-native-router-flux., but:

Warning: Failed prop type: Required prop location was not specified in... Cannot read property 'replace' of undefined

Could you point me where location should be specified or may be I need to use something else than "Actions.replace" ?

// Redirects to /login by default
const UserIsAuthenticated = UserAuthWrapper({
  authSelector: state => state.auth, // how to get the user state
  predicate: auth => auth.isAuthenticated,
  redirectAction: Actions.replace, // the redux action to dispatch for redirect
  wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
});
...
    return (
      <RouterWithRedux>
        <Scene key="tabbar" tabs={true} >
          <Scene key="authForm" component={AuthForm} title="Auth" initial={true} />
          <Scene key="register" component={UserIsAuthenticated(Register)} title="Register" />
        </Scene>
      </RouterWithRedux>
    );

alexicum avatar Jul 26 '16 08:07 alexicum

Thanks for the note, I haven't used RNRF with redux-auth-wrapper but Im pretty interested in supporting this.

It makes sense that you'd get a failed proptype there because its expecting to get the router location object and RNRF doesn't seem to give something like that. At some point we may need to provide some enhancer to pull RNRF routing specific data out to be used in a similar way. Provided you use the allowRedirectBack: false it shouldn't matter to have that warning (it'll go away in production).

The replace of undefined is a bit more troubling, just looking at it without any context seems like Actions isn't being imported correctly. The main issue though is that that redirectAction is expected currently to be a redux-action, that is then dispatched. Does RNRF support dispatching router actions in this way? You might need to define a small middleware that takes RNRF redux actions and invokes them, much like how react-router-redux does it for history (https://github.com/reactjs/react-router-redux/blob/master/src/middleware.js).

@DveMac was the one who added support for RN, have you been using RNRF at all?

mjrussell avatar Jul 26 '16 22:07 mjrussell

Thank you for explanation. Now playing with react-native-router-flux to better understand it. Will come back later.

alexicum avatar Jul 27 '16 14:07 alexicum

@alexicum any insights/lessons learned you have into making this work would be greatly appreciated!

mjrussell avatar Jul 27 '16 14:07 mjrussell

I was aware of RNRF but not had chance to have a proper look - I will at some point, but for now I just using RR alone in my RN project and doing ugly transitions.

The error @alexicum is seeing makes sense though as RNRF doesnt use 'history' like RR does. My gut feeling is it might require more that a few changes to add support to this project.

DveMac avatar Jul 28 '16 12:07 DveMac

@mjrussell I just updated my ReactNative project to v2.0.1, this is what I'm using

package.json

  "dependencies": {
    "history": "4.6.3",
    "immutable": "3.8.1",
    "query-string": "4.3.4",
    "react": "16.0.0-alpha.12",
    "react-native": "0.45.1",
    "react-redux": "5.0.5",
    "react-router-native": "4.1.1",
    "react-router-redux": "5.0.0-alpha.6",
    "redux": "3.7.2",
    "redux-auth-wrapper": "2.0.1",
    "redux-immutable": "4.0.0",
    "redux-saga": "0.15.4",
    "reselect": "3.0.1",
    "url": "0.11.0"
  },

index.[ios|android].js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createMemoryHistory } from 'history';
import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import createSagaMiddleware from 'redux-saga';
import { combineReducers } from 'redux-immutable';
import { routerReducer, routerMiddleware, ConnectedRouter } from 'react-router-redux';
import { Route } from 'react-router-native';
import {
  AppRegistry,
  View,
} from 'react-native';

const history = createMemoryHistory({
  initialEntries: ['/'],
});

const middlewares = [
  createSagaMiddleware(),
  routerMiddleware(history),
];

const enhancers = [
  applyMiddleware(...middlewares),
];

const store = createStore(
  combineReducers({
    router: routerReducer, // other reducers here
  }),
  fromJS({}),
  compose(...enhancers)
);

const LoginComponent = Login; // anyone can access this
const LogoutComponent = WithUserProfile(Logout); // wait for the profile to be loaded
const HomeComponent = Authenticated(EmailVerified(Home)); // must be authenticated and verified email

export class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <View>
            {this.props.children}
            <Switch>
              <Route exact path="/" component={HomeComponent} />
              <Route exact path="/login" component={LoginComponent} />
              <Route exact path="/logout" component={LogoutComponent} />
            </Switch>
          </View>
        </ConnectedRouter>
      </Provider>
    );
  }
}

AppRegistry.registerComponent('BigChance', () => App);

The auth wrappers are defined as

// Library
import connectedAuthWrapper from 'redux-auth-wrapper/connectedAuthWrapper';
import { connectedReduxRedirect } from 'redux-auth-wrapper/history4/redirect';
import { replace } from 'react-router-redux';
// Project
import {
  makeSelectIsLoggedIn,
  makeSelectIsInitializingAuth,
  makeSelectIsEmailVerified,
} from 'app/containers/Auth/selectors';
import LoadingPage from 'app/components/LoadingPage';

const initialising = makeSelectIsInitializingAuth();
const afterInit = (check = () => true) => (state) => (initialising(state) === false && check(state));

export const Authenticated = connectedReduxRedirect({
  wrapperDisplayName: 'Authenticated',
  authenticatedSelector: afterInit(makeSelectIsLoggedIn()),
  authenticatingSelector: initialising,
  AuthenticatingComponent: LoadingPage,
  redirectPath: '/logout',
  redirectAction: replace,
  allowRedirectBack: true,
});

export const EmailVerified = connectedReduxRedirect({
  wrapperDisplayName: 'EmailVerified',
  authenticatedSelector: afterInit(makeSelectIsEmailVerified()),
  authenticatingSelector: initialising,
  AuthenticatingComponent: LoadingPage,
  redirectPath: '/not-verified',
  redirectAction: replace,
  allowRedirectBack: true,
});

export const WithUserProfile = connectedAuthWrapper({
  wrapperDisplayName: 'WithUserProfile',
  authenticatedSelector: afterInit(),
  authenticatingSelector: initialising,
  AuthenticatingComponent: LoadingPage,
  FailureComponent: LoadingPage,
});

piuccio avatar Jul 20 '17 05:07 piuccio

@piuccio I think you forgot import {Switch} from 'react-router-native';

samuelchvez avatar Oct 08 '17 13:10 samuelchvez

You're right

piuccio avatar Oct 08 '17 13:10 piuccio

I vote on @piuccio example to be part of redux-auth-wrapper examples for React Native, I'm using on two projects here without any trouble.

ararog avatar Oct 19 '17 20:10 ararog