Ad

SetState() On Root Container Doesn't Keep Routes Of React-navigation (V3)

I have a root Component (App) which renders a nested navigation as shown in the code. Inside of app, I have the user object (stored in state) which is used by all child objects. It contains information about the groups you're in.

export default class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            user: null
        }
    }
    render() {
        if (!this.state.user) {
            // from the login component, I make an API call to my backend.
            // If the user logs in, I do app.setState({user: loggedInUser}) from inside the LoginComponent
            return <LoginComponent app={this} />
        }
        return createAppContainer(createSwitchNavigator({
            MainApp: {
                screen: createBottomTabNavigator({
                    StartPage: {
                        screen: ({ navigation }) => {
                            return <StartPage navigation={navigation} app={this} />
                        }
                    },
                    Groups: {
                        screen: createStackNavigator({
                            ListGroups: {
                                // When clicking on a Group from the GroupsPage, I execute:
                                // this.props.navigation.navigate('GroupDetail', { group, app })
                                // (from inside the GrousPage screen)
                                screen: ({ navigation }) => <GroupsPage navigation={navigation} app={this} />
                            },
                            GroupDetail: {
                                // Inside the GroupDetail, you can leave or join a group.
                                // If you do that, I'm making an API call and get the new user object.
                                // Then, I do this.props.navigation.getParam('app').setState({user: newUser})
                                // "app" was passed from ListGroups
                                screen: GroupDetail
                            }
                        })
                    }
                })
            }
        }))
    }
}

Now, when I'd like to set the updated user (from GroupDetail via app.setState({user: newUser})), the navigation doesn't keep its route and goes back to StartPage. However, what I wanted instead is to re-render GroupDetail with the new user.

How would I be able to keep the navigation state? Or do you think I have a design flaw and any idea on fixing it? Thanks!

(Yes, I'd like to keep the user object only inside of App and pass it down. Main reason is to only have few API calls)

Ad

Answer

According to docs, you have to persist the user navigation state.

read more here.

Ad
source: stackoverflow.com
Ad