Check for my variable in the redux state before proceeding

Currently, I am creating connection and registration screens, with a profile button on the bottom tab bar. The objective is for the user to be directed to their profile page if they are logged in (user data stored in Redux), or to a landing screen with login and subscribe buttons if not.

I'm wondering how to automatically navigate to the landing page whenever the "Profile" button on the bottom tab bar is clicked and the Redux store is empty.

Below is the code snippet for the profile:

// Screens / Profil.js

import React from "react";
import { StyleSheet, View, Text, Button } from "react-native";
import { color } from "../constants/color";
import { connect } from "react-redux";

class Profil extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    if (this.props.currentUser === null) {
      this.props.navigation.navigate("Landing");
    }
  }

  render() {
    const { currentUser } = this.props;
    console.log(currentUser);
    if (currentUser === null) {
      return (
        <View style={styles.mainContainer}>
          <Text>You are not connected</Text>
        </View>
      );
    } else {
      return (
        <View style={styles.mainContainer}>
          <Text>Welcome {currentUser.user.username}</Text>
          <Button title="Log out" onPress={this._disconnection} />
        </View>
      );
    }
    return null;
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: color.whisper
  }
});

const mapStateToProps = state => {
  return {
    currentUser: state.connection.currentUser
  };
};

export default connect(mapStateToProps)(Profil);

Initially, when I click on Profile, it correctly redirects me to the landing page:

However, upon clicking on Profile again, it does not redirect me back to the landing page:

I suspect this issue arises due to the component not re-rendering itself. How can I ensure constant redirection based on the Redux state variable?

UPDATE: My stack Navigator

const ProfilStackNavigator = createStackNavigator({
  Profil: {
    screen: Profil,
    navigationOptions: {
      title: "Profil"
    }
  },
  Landing: {
    screen: Landing,
    headerMode: "none",
    navigationOptions: {
      header: null
    }
  },
  SignUp: {
    screen: SignUp,
    navigationOptions: {
      title: "Inscription"
    }
  },
  SignIn: {
    screen: SignIn,
    navigationOptions: {
      title: "Connection"
    }
  }
});

Answer №1

If you're faced with this challenge, there are a couple of pathways you can take to overcome it. The first option involves utilizing the NavigationEvents feature, while the second option delves into the world of navigationOptions.

For the first option, consider adding a didFocus listener to your profile component, which triggers when the profile tab gains focus.

class Profil extends React.Component {

  subscribe = null;

  constructor(props){}

  focused = () => {
    if (this.props.currentUser == null) {
      this.props.navigation.navigate('Landing');
    }
  };

  componentDidMount = () => {
    this.subscribe = this.props.navigation.addListener('didFocus', this.focused);
  };

  componentWillUnmount() {
    this.subscribe && this.subscribe.remove();
    this.subscribe = null;
  }

  render() {
   ...
  }
}

Alternatively, for the second option, using navigationOptions, incorporate tabBarOnPress to trigger an action upon clicking the tabbar.

Profil: {
  screen: ProfilStackNavigator,
  navigationOptions: {
    tabBarLabel: 'Profil',
    tabBarOnPress: ({ navigation, defaultHandler }) => {
      // console.log('Pressed');
      defaultHandler();
    },
  },
},

Answer №2

I have achieved success with this task, and it seems like you are on the right track.

Have you considered that the navigation object might be causing the issue?

For example, I once developed a 3D Earthquake Visualizer using React/Redux/Three. In the project, I passed the history object as a prop to my components to dynamically change the routing (example code snippet omitted).

My recommendation would be to double-check your router API and log the state in the componentWillMount lifecycle method.

I hope these suggestions prove helpful. Best of luck! :)

const mapStateToProps = state => {
   return {
      ...
      quakes: state.viz.quakes,
      ...
   };
};

componentDidMount(){
   // if data hasn't download redirect to splash
   if (this.props.quakes[this.props.feedIndex].length === 0) {
     this.props.history.push("/"); 
   }
   ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nightwatch.js feature not functioning properly in a 'closing' manner

I'm facing an issue where I need to execute a function at the beginning of my test before proceeding with the rest of the test steps. Here is the custom command I am using, named internalAdviceLinksHtml: const solr = require('solr-client') ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Error message: 'Encountered issue with react-router-V4 and the new context API in React

Currently, I am experimenting with the integration of React Router V4 alongside the new React context API. Below is the code snippet I am working with: class App extends Component { static propTypes = { router: PropTypes.func.isRequired, ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...

Failure encountered when attempting to load JSON data into datalist

I've been trying to incorporate inputs into a datalist in two different ways. However, I've encountered an issue with the first method not working properly. --> Check it out on bootlply var dataList = document.getElementById('json-datalist ...

Customize the size of data points on your Angular 2 chart with variable

In my Angular 2 application, I am utilizing ng2-charts to create a line chart. The chart functions properly, showing a change in color when hovering over a point with the mouse. However, I want to replicate this behavior manually through code. Upon clicki ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

The reason why setting height to 0 is ineffective in a CSS definition

Within my current project, I am utilizing vue.js 2 and have implemented an img component. Below is the code for this component: <template> <div class="banner"> <img class="banner-img" :src="bannerImg"/> </div> </template> ...

Redux token authentication currently does not persist data in local storage after a page refresh

After implementing react-token-auth for login functionality, the login process is successful and the token is stored in local storage. However, upon refreshing the page, the data in the local storage becomes undefined. I checked the issues page on their g ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Encountering a "args" property undefined error when compiling a .ts file in Visual Studio Code IDE

I've created a tsconfig.json file with the following content: { "compilerOptions": { "target": "es5" } } In my HelloWorld.ts file, I have the following code: function SayHello() { let x = "Hello World!"; alert(x); } However ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

Receiving an error message stating "Uncaught SyntaxError: Unexpected token <" in React while utilizing the AWS SDK

Each time I execute 'npm run build' in main.js, an error keeps popping up: Uncaught SyntaxError: Unexpected token < The error vanishes after refreshing the page. Upon investigation, I discovered that two libraries are causing this problem: ...

Updating data from an API within a div using AJAX calls in a React application

I have designed a React template to showcase live football scores in the following manner: const LiveScore = () => { const {direction} = useThemeProvider(); const [selectedDay, setSelectedDay] = useState(parseInt(dayjs().format('DD'))); retur ...

Implementing React and Material UI - Customizing Navigation Buttons/Links according to Routes

The following code snippet represents the main entry point of a React app, app.js, which includes the router endpoints. Below the app.js code, you will find the code for a Nav component, which serves as the navigation menu. I am looking to structure this ...