Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example for React Native #34

Open
mjrussell opened this issue Apr 26, 2016 · 9 comments
Open

Example for React Native #34

mjrussell opened this issue Apr 26, 2016 · 9 comments

Comments

@mjrussell
Copy link
Owner

#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.

@alexicum
Copy link

alexicum commented Jul 26, 2016

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>
    );

@mjrussell
Copy link
Owner Author

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?

@alexicum
Copy link

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

@mjrussell
Copy link
Owner Author

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

@DveMac
Copy link
Contributor

DveMac commented Jul 28, 2016

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.

@piuccio
Copy link
Contributor

piuccio commented Jul 20, 2017

@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,
});

@samuelchvez
Copy link

samuelchvez commented Oct 8, 2017

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

@piuccio
Copy link
Contributor

piuccio commented Oct 8, 2017

You're right

@ararog
Copy link

ararog commented Oct 19, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants