I observed that this problem is common, but I didn't find a solution for my case.
I'm trying to redirect the user to another navigator in react native, using react and redux with redux-thunk. If I display just Home screen it works fine, but when I'm redirecting from SignIn screen to Home, it goes into an infinite loop, I found the problem is in the dispatch function.
import {
FETCHING_CATEGORIES_REQUEST,
FETCHING_CATEGORIES_SUCCESS,
FETCHING_CATEGORIES_FAILURE,
} from "../types"
import { Categories } from "../../services/firebase"
export const fetchingCategoriesRequest = () => ({
type: FETCHING_CATEGORIES_REQUEST,
})
export const fetchingCategoriesSuccess = data => ({
type: FETCHING_CATEGORIES_SUCCESS,
payload: data,
})
export const fetchingCategoriesFailure = error => ({
type: FETCHING_CATEGORIES_FAILURE,
payload: error,
})
export const fetchCategories = () => {
return async dispatch => {
dispatch(fetchingCategoriesRequest())
Categories.get()
.then(data => dispatch(fetchingCategoriesSuccess(data)))
.catch(error => dispatch(fetchingCategoriesFailure(error)))
}
}
Routing
import { createSwitchNavigator } from "react-navigation"
import PrivateNavigator from "./private"
import PublicNavigator from "./public"
const Navigator = (signedIn = false) => {
return createSwitchNavigator(
{
Private: {
screen: PrivateNavigator,
},
Public: {
screen: PublicNavigator,
},
},
{
initialRouteName: signedIn ? "Private" : "Public",
},
)
}
export default Navigator
Redirecting
import React from "react"
import { Spinner } from "native-base"
import { connect } from "react-redux"
import Navigator from "../navigation"
class AppContainer extends React.Component<any, any> {
render() {
const { isLogged, loading } = this.props.auth
const Layout = Navigator(isLogged)
return loading ? <Spinner /> : <Layout />
}
}
const mapStateToProps = state => {
return {
...state,
}
}
export default connect(
mapStateToProps,
{},
)(AppContainer)
Be careful with mapStateToProps
, you should only select the part of the store you're interested in, otherwise performance problems could occur
const mapStateToProps = state => ({auth: state.auth});
A little explanation how react-redux connect
works,
mapStateToProps
functions of all the connected components are executed===
is used) then the component is re-rendered otherwise it does nothing.In your example, as you select all the props of the store, your component will be re-rendered for each modification in the store
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With