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:

https://i.sstatic.net/fLeEn.jpg

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

https://i.sstatic.net/hFMdt.jpg

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

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

When refreshing the React page, it appears blank

Encountering a issue with one of the pages on my react website. Whenever I attempt to reload the Home.js page by refreshing the browser, it displays blank. However, when using the back navigation button in the browser, it functions correctly. I've che ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Guidance on calling a JavaScript function from a dynamically added control

The Master page includes a ScriptManager. Next, I have a Control with a ScriptManagerProxy and an UpdatePanel. Within the UpdatePanel, I dynamically insert another Control (which also has a ScriptManagerProxy) that needs to run some JavaScript code. In ...

Can you explain the meaning of the code snippet provided?

<script type="text/javascript> window.onload = function(){ //execute some code here },function(){ // execute another piece of code here }(); </script> Is this code indicating that multiple function ...

Can Ajax and jQuery be utilized on a webpage in conjunction with a cron job?

These are the steps my page performs: Retrieve an array from a different server (first.php) Parse values using a PHP script Send parsed values using an AJAX call In the next page (second.php) that is called by AJAX, perform MySQL queries If values meet c ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Converting milliseconds to a valid date object using Angular form validation

I am facing an issue with form validation and milliseconds in my Angular application. It seems that Angular does not consider time in milliseconds as a valid date format, causing the angular.isDate(1418645071000) function to return false. How can I modify ...

Node JS Request Params 500 Error

When generating the URI, everything appears to be in order and the list data is displayed on the page. However, when sending the request in the request method, a 500 error occurs instead of the body being returned. Here is the URI: http://yufluyuinnepal.c ...

Can jQuery Autocomplete function without stopping at white spaces?

Is there a way to modify jQuery UI autocomplete so that it can handle multiple words instead of terminating with a space? For example, if you input "New York City", it should still filter results based on each word. $.ajax({ type: "GET" ...

The issue of why padding left is not functioning correctly in Bootstrap version 5.3.1

</head> <body> <header class="bg-info "> <div class="container"> <div class="row text-white"> <div class="col-md-6 p-3 pl-6 "> ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Electron fails to display images in the compiled version

I'm currently troubleshooting an issue related to displaying images using CSS in my electron project. In the latest version of the application, the images are not showing up when linked from a CSS file. However, in a previous version, the images disp ...

Instructions for activating a button in the absence of any inputs

I need help enabling a button in angularjs based on whether any of the inputs are filled out. I was successful in disabling a button when only one input is checked, but how can I do this for all inputs affecting one button? This is what I've attempted ...

How can we use jQuery to compare two blocks and set them to have the same height value?

Is there a way to compare and set equal height for two blocks within the main div? <div class="main-content"> <div class="content-1"></div> <div class="content-2"></div> </div> Javascript Code: var $content1 = $(&ap ...

Encountering ENOENT error when attempting to upgrade Node from version 6 to the latest one in a React Native project causes npm

When updating npm from version 6.14 to the latest on a React Native project, I am using Node.js 14, nvm to switch between Node versions. Ideally, I would like to upgrade to Node.js 16, but I encounter a similar issue regardless of whether it's versio ...

Conceal the header and footer during the loading of particular pages

For my Angular 1.x application, I needed a way to hide the header and footer on specific pages. To achieve this, I added a 'navigateOut' data property to my state definitions. Using ng-if in my template, I was able to show/hide elements such as t ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...