Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Signinscreen`)

I am getting the following warning:

Warning: Cannot update a component (ForwardRef(BaseNavigationContainer)) while rendering a different component (Signinscreen). To locate the bad setState() call inside Signinscreen, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

Signinscreen.js

import React, { Component, useEffect } from 'react'
import { View, Text, TextInput, Image } from 'react-native'

// STYLE
import styles from "./style"

// FORMIK
import { Formik } from 'formik'

// COMPONENT
import Navigationcomponent from "../../assets/components/navigationcomponent"

// STORAGE
import AsyncStorage from '@react-native-async-storage/async-storage'

// REDUX
import { connect } from 'react-redux'

// REDUX ACTION
import { initialaccount,user_signin } from '../../actions/index'

// YUP
import * as yup from 'yup'

// IMAGE
const mainimage = require("../../assets/images/mainlogo.png")

// SCREEN
import Homescreen from "../homescreen";

const SigninSchema = yup.object().shape({
    username: yup
        .string()
        .min(6)
        .max(12)
        .required('Please, provide your username!')
        .nullable(),
    password: yup
        .string()
        .min(6)
        .required('Please, provide your password!')
        .nullable(),
})

const Signinscreen = ({navigation, initialaccount_d, user_signin_d, user_s}) => {
    const storeData = async (values) => {
        try {
            // await AsyncStorage.setItem('me', JSON.stringify(values))
            // await initialaccount_d(true)
            // console.log(values)
            await user_signin_d(values)
            // 
            // navigation.navigate("Initialhomescreen")
        } catch (e) {
          // saving error
        }   
                
    }


    const validatecheck = () => {  
        AsyncStorage.setItem('me', JSON.stringify(user_s.usersignin_success))
        navigation.navigate("Initialhomescreen")
        // console.log(user_s.usersignin_success)
        // if (user_s.usersignin_success != null) {
        //     // console.log(user_s.usersignin_success)
        //     // navigation.navigate("Initialhomescreen")
            
        //     if (user_s.usersignin_success.status == 200) {
        //         // console.log("user_s.usersignin_success")
        //         await AsyncStorage.setItem('me', JSON.stringify(user_s.usersignin_success))
        //         navigation.navigate("Initialhomescreen")
        //     }    
        // } 
    }
    
    // ONBACK PRESS
    useEffect(() => {
        // validatecheck()
        navigation.addListener('beforeRemove', e => {
            // REMOVE INPUT VALUE BEFORE LEAVE SCREEN
            user_signin_d(null)
        });
    },[])

    if (user_s.usersignin_success != null && user_s.usersignin_success.status == 200) {
        // validatecheck()
        return(
            <View>
                {validatecheck()}
                <Text>Load...</Text>
            </View>
        )
    } else {
        return(
            <Formik
                // validationSchema={SigninSchema}
                initialValues={{ username: null, password: null}}
                onSubmit={values => storeData(values)}>
                    {({ handleChange, handleSubmit, values, errors, touched }) => 
                    (
                        <View style={styles.main}>
                            <View style={styles.mainconf}>
                                <Image style={styles.imageconf} source={mainimage}></Image>
                                <View style={styles.inputconfmain}>
                                    <Text style={styles.titleconf}>
                                        Create now, for ever...
                                    </Text>
                                    <TextInput
                                        style={styles.inputconf}
                                        placeholder="username"
                                        placeholderTextColor="gray"
                                        onChangeText={handleChange('username')}
                                        value={values.username}>
                                    </TextInput>
                                    {touched.username && errors.username &&
                                        <Text style={{ fontSize: 12, color: 'red', alignSelf: "center" }}>{errors.username}</Text>
                                    }         
                                    <TextInput
                                        style={styles.inputconf}
                                        placeholder="password"
                                        placeholderTextColor="gray"
                                        secureTextEntry={true}
                                        onChangeText={handleChange('password')}
                                        value={values.password}>
                                    </TextInput>
                                    {touched.password && errors.password &&
                                        <Text style={{ fontSize: 12, color: 'red', alignSelf: "center" }}>{errors.password}</Text>
                                    }  
                                    <Text onPress={handleSubmit} style={styles.btnsignupconf}>
                                        Sign in
                                    </Text>
                                    {user_s.usersignin_success != null ? (user_s.usersignin_success.status == 400 ? <Text style={styles.warningmsg}>{user_s.usersignin_success.message}</Text> : (null)) : null}
                                </View>
                            </View>
                        </View>
                    )}
            </Formik> 
        )
    }
}

const mapStateToProps = (state) => ({
    user_s: state.user
})
  
const mapDispatchToProps = (dispatch) => ({
    initialaccount_d: (value) => dispatch(initialaccount(value)),
    user_signin_d: (value) => dispatch(user_signin(value))
})
  
export default connect(mapStateToProps, mapDispatchToProps)(Signinscreen)

Homescreen.js

import React, { Component, useEffect, useState } from 'react'
import { View, Text, Image, SafeAreaView, BackHandler } from 'react-native'

// COMPONENT
import Navigationcomponent from "../../assets/components/navigationcomponent";

// STORAGE
import AsyncStorage from '@react-native-async-storage/async-storage';

// STYLE
import styles from "./style"

// REDUX
import { connect } from 'react-redux'

// REDUX ACTION
import { initialaccount } from '../../actions/index'

const Homescreen = ({navigation, initialaccount_s, initialaccount_d, user_s}) => {
//   useEffect(() => {
//     myaccount()
//   }, []);

//   myaccount = async () => {
//     try {
//       const value = await AsyncStorage.getItem('me')
//       if(value !== null) {
//         // value previously stored
//         console.log('Yay!! you have account.')
//         // await navigation.navigate("Homescreen")   
//         await initialaccount_d(true)
//       } else {
//         console.log('Upss you have no account.')
//         // await navigation.navigate("Welcomescreen")   
//         await initialaccount_d(false)
//       }
//     } catch(e) {
//       // error reading value
//     }
//   }

  // Call back function when back button is pressed
  const backActionHandler = () => {
    BackHandler.exitApp()
    return true;
  }

  useEffect(() => {
    console.log(user_s.usersignin_success)
    // Add event listener for hardware back button press on Android
    BackHandler.addEventListener("hardwareBackPress", backActionHandler);
    return () =>
      // clear/remove event listener
      BackHandler.removeEventListener("hardwareBackPress", backActionHandler);
  },[])

  // const validatecheck = () => {  
  //   console.log(user_s.usersignin_success)
  //   // if (user_s.usersignin_success == null || user_s.usersignin_success.status == 400) {
  //   //   navigation.navigate("Signinscreen")
  //   // }
  // }

  clearAll = async () => {
    try {
      await AsyncStorage.clear()
      await initialaccount_d(false)
      navigation.navigate("Initialscreen")
      console.log('Done. cleared')
    } catch(e) {
      console.log('Upss you have no account.')
    } 
  }

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('me')
      if(value !== null) {
        // value previously stored
        console.log(value)
      } else {
        console.log('Upss you have no account.')
      }
    } catch(e) {
      // error reading value
    }
  }

  return(
        <View style={styles.main}>
          <View style={styles.logoutconf}>
            <Text onPress={() => clearAll()}>LOGOUT</Text>
            <Text onPress={() => getData()}>cek data</Text>
            </View>
          <Navigationcomponent style={styles.mainconf} />
        </View>
  )
}

const mapStateToProps = (state) => ({
  initialaccount_s: state.user,
  user_s: state.user
})

const mapDispatchToProps = (dispatch) => ({
  initialaccount_d: (value) => dispatch(initialaccount(value))
})

export default connect(mapStateToProps, mapDispatchToProps)(Homescreen)
like image 348
ImNewBtw Avatar asked Oct 23 '25 13:10

ImNewBtw


1 Answers

I encountered the same problem and I think that passing navigation.navigate("<screen_name>");} to another screen's onPress() prop (like

onPress={() => {navigation.navigate("<screen_name>");}

or

...
const navFunction = () => {
  navigation.navigate("<screen_name>");
};

return(
  <TouchableOpactiy onPress={() => {navFunction();} />
    ... 
  </TouchableOpacity>
);
...

).

I solved this by not passing the navigation from the onPress prop in the homeScreen and instead using the navigation prop inherent to the otherScreen.

//  The homescreen.
const App = props => {
  return(
    <TouchableOpactiy 
      onPress={() => {
        props.navigation.navigate('OtherScreen');
      }} 
    >...</TouchableOpacity>
  );
};
//  The other screen.
const App = ({navigation}) => {
  return(
    <TouchableOpacity 
      onPress={() => {
        navigation.navigate('HomeScreen');
      }} 
    >...</TouchableOpacity>
  );
};

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!