Why is my navigation ref not ready in React Navigation 6 with Redux? - react-native

In React Navigation 6, my research shows that to navigate without a prop I should make a reference and use createNavigationContainerRef. I'm able to pass down the screen name to my dispatch but for some reason when I evaluate the condition with isReady I'm always told it isn't. The code:
App.js:
import React from 'react'
import { NavigationContainer } from '#react-navigation/native'
import 'react-native-gesture-handler'
// Provider
import { Provider as AuthProvider } from './src/context/AuthContext'
// Navigation
import { navigationRef } from './src/navigation/NavRef'
// Screens
import ResolveAuthScreen from './src/screens/ResolveAuthScreen'
const App = () => {
return (
<AuthProvider>
<NavigationContainer ref={navigationRef}>
<ResolveAuthScreen />
</NavigationContainer>
</AuthProvider>
)
}
export default App
ResolveAuthScreen.js:
import React, { useEffect, useContext } from 'react'
// Context
import { Context as AuthContext } from '../context/AuthContext'
const ResolveAuthScreen = () => {
const { tryLocalSignIn } = useContext(AuthContext)
useEffect(() => {
tryLocalSignIn()
}, [])
return null
}
export default ResolveAuthScreen
AuthContext.js (stripped down):
import AsyncStorage from '#react-native-async-storage/async-storage'
// Context
import createContext from './createContext'
// Nav
import * as NavRef from '../navigation/NavRef'
const authReducer = (state, action) => {
switch (action.type) {
case 'signin':
return { errorMessage: '', token: action.payload }
case 'clear_error':
return { ...state, errorMessage: '' }
default:
return state
}
}
const tryLocalSignIn = dispatch => async () => {
const token = await AsyncStorage.getItem('token')
console.log({ token }) // renders token
if (token) {
dispatch({ type: 'signin', payload: token })
NavRef.navigate('TrackListScreen')
} else {
NavRef.navigate('SignUp')
}
}
export const { Provider, Context } = createContext(
authReducer,
{ tryLocalSignIn },
{ token: null, errorMessage: '' },
)
NavRef.js:
import { createNavigationContainerRef } from '#react-navigation/native'
export const navigationRef = createNavigationContainerRef()
export function navigate(name, params) {
console.log({ name, params })
if (navigationRef.isReady()) {
console.log('ready')
console.log({ name, params })
navigationRef.navigate('TrackDetailScreen', { name, params })
} else {
console.log('not ready')
}
}
When I log the token from dispatch I get back the token. When I log the screen I get back TrackListScreen from navigate but whenever it's fired it always returns the console log of not ready.
Docs:
Navigating without the navigation prop
Navigating to a screen in a nested navigator
"dependencies": {
"#react-native-async-storage/async-storage": "~1.15.0",
"#react-navigation/bottom-tabs": "^6.0.9",
"#react-navigation/native": "^6.0.6",
"#react-navigation/native-stack": "^6.2.5",
"axios": "^0.24.0",
"expo": "~43.0.0",
"expo-status-bar": "~1.1.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.2",
"react-native-elements": "^3.4.2",
"react-native-gesture-handler": "~1.10.2",
"react-native-reanimated": "~2.2.0",
"react-native-safe-area-context": "3.3.2",
"react-native-screens": "~3.8.0",
"react-native-web": "0.17.1"
},
Why is my navigate not working after my dispatch or why does the isReady false?

I'm having the same issue. When trying to access the exported navigationRef.isReady() from a redux-saga file, it always returns false. I'm not sure this is a safe approach, nor have I properly tested this, but the following workaround seems to work for me:
App.js
import {setNavigationRef, navigationIsReady} from './NavigationService';
const navigationRef = useNavigationContainerRef();
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
setNavigationRef(navigationRef);
}}>
...
</NavigationContainer>
);
NavigationService.js
export let navigationRefCopy = undefined;
export function setNavigationRef(navigationRef) {
navigationRefCopy = navigationRef;
}
export function navigationIsReady() {
return navigationRefCopy?.isReady(); // returns true when called in a redux saga file.
}

Related

How to stop Fast refresh reset route to initialRoute automatically in React Native

How are you.
I am using React Native 0.62.2.
The problem is when code updated, it goes to initalRoute automatically, so I need to navigate to screen I was working to check updated.
How can I stop it so when updated code, fast refresh shows update on current screen?
"react": "16.11.0",
"react-native": "0.62.2",
"#react-navigation/bottom-tabs": "^5.2.7",
"#react-navigation/drawer": "^5.5.0",
"#react-navigation/material-bottom-tabs": "^5.1.9",
"#react-navigation/native": "^5.1.5",
"#react-navigation/stack": "^5.2.10",
Thanks
For those who are running into this problem with React Native Web.
I fixed this by configuring Linking with React Navigation.
const config = {
screens: {
Login: 'login',
Home: '',
About: 'about',
},
};
const linking = {
prefixes: ['https://example.com',],
config,
};
<NavigationContainer linking={linking}>
...
</NavigationContainer>
Once Linking was set up, fast refresh no longer reseted the navigation to the first route.
You can write a component that record the state of the navigation and stores it on asyncStorage. Maybe something like so:
import { InitialState, NavigationContainer } from "#react-navigation/native";
import React, { useCallback, useEffect, useState } from "react";
import { AsyncStorage } from "react-native";
const NAVIGATION_STATE_KEY = `NAVIGATION_STATE_KEY-${sdkVersion}`;
function NavigationHandler() {
const [isNavigationReady, setIsNavigationReady] = useState(!__DEV__);
const [initialState, setInitialState] = useState<InitialState | undefined>();
useEffect(() => {
const restoreState = async () => {
try {
const savedStateString = await AsyncStorage.getItem(
NAVIGATION_STATE_KEY
);
const state = savedStateString
? JSON.parse(savedStateString)
: undefined;
setInitialState(state);
} finally {
setIsNavigationReady(true);
}
};
if (!isNavigationReady) {
restoreState();
}
}, [isNavigationReady]);
const onStateChange = useCallback(
(state) =>
AsyncStorage.setItem(NAVIGATION_STATE_KEY, JSON.stringify(state)),
[]
);
if (!isNavigationReady) {
return <AppLoading />;
}
return (
<NavigationContainer {...{ onStateChange, initialState }}>
{children}
</NavigationContainer>
);
}
I'd check LoadAsset Typescript component from #wcandillon here
Maybe you can try this way.
I follow the State persistence document of React Navigation to write the code down below.
https://reactnavigation.org/docs/state-persistence/
import * as React from 'react';
import { Linking, Platform } from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import { NavigationContainer } from '#react-navigation/native';
const PERSISTENCE_KEY = 'NAVIGATION_STATE';
export default function App() {
const [isReady, setIsReady] = React.useState(__DEV__ ? false : true);
const [initialState, setInitialState] = React.useState();
React.useEffect(() => {
const restoreState = async () => {
try {
const initialUrl = await Linking.getInitialURL();
if (Platform.OS !== 'web' && initialUrl == null) {
// Only restore state if there's no deep link and we're not on web
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString ? JSON.parse(savedStateString) : undefined;
if (state !== undefined) {
setInitialState(state);
}
}
} finally {
setIsReady(true);
}
};
if (!isReady) {
restoreState();
}
}, [isReady]);
if (!isReady) {
return <ActivityIndicator />;
}
return (
<NavigationContainer
initialState={initialState}
onStateChange={(state) =>
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))
}
>
{/* ... */}
</NavigationContainer>
);
}

react-redux-firebase Firestore not ever loading the data

I have a react-native app that is using react-redux-firebase, react-native-firebase to connect to a firestore to return some todo records. There are records in the store, however all that is displayed is the "loading" text. It never updates the todos.
I have tried connecting directly within the app and it works fine so I'm assuming that firebase is configured correctly.
this.ref.get().then((querySnapshot) => {
console.log("ListItemFS: started query snapshot", querySnapshot);
this.handleSnapshot(querySnapshot);
});
This is my App.tsx
import React from 'react'
import { Provider } from 'react-redux'
import { ReactReduxFirebaseProvider } from 'react-redux-firebase';
import firebase from 'react-native-firebase'
import { createStore, compose } from 'redux'
import { composeWithDevTools } from "redux-devtools-extension";
import { createFirestoreInstance, firestoreReducer } from 'redux-firestore'
import { combineReducers } from 'redux';
import { firebaseStateReducer } from 'react-redux-firebase'
import Todos from './Todos';
//Configure firebase
const fbConfig = {
userProfile: 'users',
useFirestoreForProfile: true, // Firestore for Profile instead of Realtime DB,
enableLogging: true
}
//firebase.initializeApp(fbConfig) // <- I have tried with and without this with no difference.
//let db = firebase.firestore(); makes no difference
//Configure reducers
const rootReducer = combineReducers({
firebase:firebaseStateReducer,
firestore: firestoreReducer
})
// Configure store
const store = createStore(rootReducer, compose(composeWithDevTools()))
export default () => (
<Provider store={store}>
<ReactReduxFirebaseProvider
firebase={firebase}
config={fbConfig}
dispatch={store.dispatch}
createFirestoreInstance={createFirestoreInstance}
>
<Todos />
</ReactReduxFirebaseProvider>
</Provider>
)
This is my TODO component
import React from 'react'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { isLoaded, isEmpty } from 'react-redux-firebase/lib/helpers'
import { View ,Text} from 'react-native'
import { firestoreConnect } from 'react-redux-firebase'
function Todos({ todos, firebase, state }) {
console.log("ToDos",todos);
console.log("state",state);
if (!isLoaded(todos)) {
return <Text>Loading...</Text>
}
if (isEmpty(todos)) {
return <Text>Todos List Is Empty</Text>
}
return (
<View>
{
Object.keys(todos).map(
(key, id) => (
<Text >First Key:{todos[key]}</Text>
)
)
}
</View>
)
}
export default compose(
firestoreConnect(() => [
{ collection: 'todos' } //'todos' // { path: '/todos' } // neither works
]),
connect(state => ({
todos: state.firestore.data.todos
// profile: state.firebase.profile // load profile
}))
)(Todos)
The following are my dependencies
"dependencies": {
"expo": "^34.0.1",
"fbjs": "^1.0.0",
"react": "16.8.3",
"react-dom": "16.8.3",
"react-native": "0.59.10",
"react-native-firebase": "5.2.0",
"react-native-gesture-handler": "~1.3.0",
"react-native-reanimated": "~1.1.0",
"react-native-router-flux": "^4.1.0-beta.8",
"react-native-screens": "1.0.0-alpha.22",
"react-native-size-matters": "^0.2.1",
"react-native-unimodules": "~0.5.2",
"react-native-web": "^0.11.4",
"react-navigation-deprecated-tab-navigator": "^1.3.0",
"react-redux": "^5.0.6",
"react-redux-firebase": "^3.0.0-beta.2",
"recompose": "^0.30.0",
"redux": "3.x.x",
"redux-devtools-extension": "^2.13.8",
"redux-firestore": "^0.8.0"
}
If you have any suggestions on what I've done wrong I would be really grateful.
Try to add
import 'react-native-firebase/firestore'
in your App.tsx

Invariant Violation: Element type is invalid: expected a string using connect of react-redux

Supposedly, I've got a small problem, but can't tackle it.
I've got a small React-Native app, one screen only.
Redux is used as a store. It's being built via Expo. While using connect of react-redux, I've got the following error:
Invariant Violation: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of Home.
The app works if the component rendered by Home component isn't wrapped by connect().
Attach some code below.
App.js
import React from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Home from './src/pages/Home';
import { Provider } from 'react-redux';
import configureStore from './src/stores/store';
const { store } = configureStore();
function App() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
)
}
const MainNavigator = createStackNavigator({
Home: { screen: Home }
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
}
);
const AppContainer = createAppContainer(MainNavigator);
export default App;
Home.js
import React from "react";
import { StyleSheet, View, Text, Dimensions } from "react-native";
import SwitchEventTypes from "../components/SwitchEventTypes";
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<View>
<SwitchEventTypes />
</View>
)
}
}
SwitchEventTypes.js
import React, { Component } from "react";
import { connect } from 'react-redux';
import { StyleSheet, View, Text, Dimensions, TouchableOpacity } from "react-native";
import { updateEventType } from '../actions/actions';
const mapDispatchToProps = (dispatch) => {
return {
updateEventType: (newEventType) => {
dispatch(updateEventType(newEventType));
}
};
};
const mapStateToProps = (state) => {
return {
eventType: state.filter.eventType,
};
};
class SwitchEventTypes extends React.Component {
constructor() {
super();
this.state = {
isSwitchEventTypeOn: true
}
this.handleEventTypeChange = this.handleEventTypeChange.bind(this);
}
handleEventTypeChange(newEventType) {
this.props.updateEventType(newEventType);
}
render() {
return (
<View style={styles.switchTypesContainer}>
{this.props.eventType === 'active' ? <Text>123</Text> :
<Text>456</Text>
}
</View>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SwitchEventTypes);
store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const middleware = [thunk];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const composedEnhancers = composeEnhancers(
applyMiddleware(...middleware),
)
export default () => {
const store = createStore(rootReducer, composedEnhancers);
return { store };
};
package.json
"dependencies": {
"expo": "^32.0.6",
"expo-react-native-shadow": "^1.0.3",
"expo-svg-uri": "^1.0.1",
"prop-types": "^15.7.2",
"react": "16.8.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.1.tar.gz",
"react-native-calendars": "^1.32.0",
"react-native-svg": "^9.4.0",
"react-navigation": "^3.9.1",
"react-redux": "^7.0.1",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"react-native-switch": "^1.5.0"
},
"devDependencies": {
"babel-preset-expo": "^5.0.0",
"redux-devtools-extension": "^2.13.8",
"schedule": "^0.4.0"
},
What may be the matter? Please, help. Thanks.
Your mapDispatchToProps is returning an object. You also don't need the extra returns as fat arrow functions already have an implicit return. Will make your code a little more readable.
const mapDispatchToProps = dispatch => ({
updateEventType: (newEventType) => dispatch(updateEventType(newEventType));
});
const mapStateToProps = state => {
eventType: state.filter.eventType, // might be worth your time to investigate selectors down the road
};

ReactNavigation Error - Cannot read property 'bind' of undefined

"react-native": "^0.57.0",
"react-navigation": "^3.0.0",
"react-navigation-redux-helpers": "^2.0.7",
"react-redux": "^5.0.6",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0",
"reduxsauce": "0.7.0",
"react-native-gesture-handler": "^1.0.9",
Updating react-navigation to 3.0.0 in my React-Native app. I have followed the official docs here React Navigation and installed all the dependencies.
However cannot resolve this issue.
AppNavigation.js
const PrimaryNav = createStackNavigator({
HomeScreen: {
screen: MainTabNav,
}, {
mode: 'modal',
headerMode: 'none',
initialRouteName: 'HomeScreen',
navigationOptions: {
headerStyle: styles.header,
},
});
export default createAppContainer(PrimaryNav);
ReduxNavigation.js
import AppNavigation from './AppNavigation';
import { reduxifyNavigator, createReactNavigationReduxMiddleware } from
'react-navigation-redux-helpers';
createReactNavigationReduxMiddleware(
'root',
state => state.nav,
);
const ReduxAppNavigator = reduxifyNavigator(AppNavigation, 'root');
render() {
const { dispatch, nav } = this.props;
<ReduxAppNavigator state={nav} dispatch={dispatch} />
}
const mapStateToProps = state => ({ nav: state.nav });
export default connect(mapStateToProps)(ReduxNavigation);
navigation.js
import { Keyboard } from 'react-native';
import AppNavigation from '../navigation/AppNavigation';
export default (state, action) => {
Keyboard.dismiss();
const newState = AppNavigation.router.getStateForAction(action, state);
return newState || state;
};
CreateStore.js
import { createStore, applyMiddleware, compose } from 'redux';
import reduxThunkMiddleware from 'redux-thunk';
import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-
helpers';
import screenTrackingMiddleware from './screenTrackingMiddleware';
export default (rootReducer) => {
const middleware = [];
const enhancers = [];
const navigationMiddleware = createReactNavigationReduxMiddleware(
'root',
state => state.nav,
);
middleware.push(screenTrackingMiddleware);
middleware.push(navigationMiddleware);
middleware.push(reduxThunkMiddleware);
enhancers.push(applyMiddleware(...middleware));
const store = createStore(rootReducer, compose(...enhancers));
return {
store,
};
};
RootContainer.js
import ReduxNavigation from 'navigation/ReduxNavigation';
export default class RootContainer extends Component {
render() {
return (
<View style={styles.applicationView}>
<StatusBar barStyle="light-content" />
<ReduxNavigation />
</View>
);
}
}
This happens because you didn't link react-native-gesture-handler
Just type react-native link in your project dir.
And run again react-native run-android
Solved the issue by adding this plugin to .babelrc file.
[
"#babel/plugin-transform-flow-strip-types",
]

middlware is not a function in react native

I am learning React-native and trying to implement redux.
I have used React-redux & React-thunk perform a Async task from the Action. During the implementation, getting an error e.i. "middleware in not a function" when I run. If I comment out middleware and relevant code then everything works fine.
Here is my code below.
index.js
import React, {Component} from 'react';
import ResetUserContainer from "./src/Components/resetUserContainer"
import {Provider} from 'react-redux'
import {createStore,applyMiddleware} from 'redux'
import {thunk} from 'redux-thunk'
import userResetReducer from "./src/Reducers/ResetReducer"
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(userResetReducer);
export default class App extends Component {
render() {
return (
<Provider store = {store}>
<ResetUserContainer/>
</Provider>
);
}
}
ResetUserContainer.js class.
import React, { Component } from "react";
import { StyleSheet, View, ActivityIndicator } from "react-native";
import { connect } from "react-redux"
import userAction from "./Actions/UserAction"
import PropTypes from "prop-types";
class ResetUserContainer extends Components {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.requestToken();
}
render() {
return (
<View style={styles.container}>
<View style={styles.subContainer}>
onPress={this._onPressButton}
containerStyle={{ marginTop: 20 }}
/>
</View>
</View>
<ActivityIndicator
size="large"
color="red"
style={this.props.isFetching ? styles.centering : styles.hideLoader} />
</View>
);
}
_onPressButton = () => {
// this.props.requestToken();
}
}
ResetUserContainer.propTypes = {
requestToken: PropTypes.func.isRequired,
objectMember: PropTypes.object.isRequired
}
const mapStateToProps = state => {
return {
//Here using objectMember, we can access any member of action class
objectMember: state,
//we can use also like this
isFetching: state.isFetching,
errorMsg: state.errorMsg,
displayMsg: state.displayMsg,
token: state.token
}
}
export default connect(mapStateToProps, { userAction })(ResetUserContainer);
types.js
export const TOKEN_REQUEST_PROCESSED = 'TOKEN_REQUEST_PROCESSED';
export const TOKEN_REQUEST_TOKEN_SUCCEEDED= 'TOKEN_REQUEST_TOKEN_SUCCEEDED';
export const TOKEN_REQUEST_FAILED = 'TOKEN_REQUEST_FAILED';
UserAction.js
import AuthInterface from '../../Interfaces/authInterface';
import UserResetModel from '../../Models/userResetModel';
import SpecialUserModel from '../../Models/specialUserModel';
import { TOKEN_REQUEST_PROCESSED, TOKEN_REQUEST_TOKEN_SUCCEEDED, TOKEN_REQUEST_FAILED } from './types';
export const tokenRequestProcess = () => ({ type: TOKEN_REQUEST_PROCESSED });
export const tokenRequestSuccess = (token) => ({ type: TOKEN_REQUEST_TOKEN_SUCCEEDED, payload: token });
export const tokenRequestFailed = (error) => ({ type: TOKEN_REQUEST_FAILED, payload: error });
export const requestToken = () => {
return async dispatch => {
dispatch(tokenRequestProcess);
let specialuser = new SpecialUserModel("", "");
specialuser.Username = "xyz.com";
specialuser.Password = "xyz.password";
AuthInterface.authenticateSpecialUser(specialuser).then((response) => {
let result = new httpResponseModel();
result = response;
if (result.ErrorCode == "OK") {
dispatch(tokenRequestSuccess(result.token_number))
} else {
//Handel all possible failure by error msg
dispatch(tokenRequestFailed(result.error_msg));
}
}, (err) => {
dispatch(tokenRequestFailed(JSON.stringify(err)));
});
}
};
ResetReducer.js
import {
TOKEN_REQUEST_PROCESSED, TOKEN_REQUEST_TOKEN_SUCCEEDED, TOKEN_REQUEST_FAILED
} from './types';
const initialState = {
isFetching: false,
errorMsg: '',
displayMsg: '',
token: ''
};
const resetReducer = (state = initialState, action) => {
switch (action.type) {
case TOKEN_REQUEST_PROCESSED:
return { ...state, isFetching: true };
case TOKEN_REQUEST_TOKEN_SUCCEEDED:
return { ...state, isFetching: false, displayMsg: action.payload }
case TOKEN_REQUEST_FAILED:
return { ...state, isFetching: false, errorMsg: action.payload }
default:
return state;
}
}
export default resetReducer;
package.json
"dependencies": {
"react": "16.5.0",
"react-native": "^0.57.2",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.48.0",
"react-test-renderer": "16.5.0"
},
Please let me know if I am doing something wrong or missing something.
I have googled but couldn't solve, like here in,
Redux thunk in react native
Thanks in advance.
import {thunk} from 'redux-thunk'
Please check this line. You should change that into below.
import thunk from 'redux-thunk'