0

I have defined a global variable in drawer component. I use this var in the same component and I change it, my approach works fine

import ....
...
const USERID_STORED = "userid_stored";
var userArray = [];
var lengthNow = 0;
...
class DrawerComponent extends React.Component {
  _goToMessages  = (route) => (
    () => {
      const navigateAction = NavigationActions.navigate({
        routeName: route
      });
      this.props.navigation.dispatch(navigateAction);
      this.props.navigation.closeDrawer();
      lengthNow = userArray.length; // change it here

    }

  );
...
render (
...
)
}

but whene I reload the App, lengthNow takes back his initial value 0

Can I let lengthNow keep its value ? how can I do it ?

if you have another aproach propose it to me please

1 Answer 1

2

It is better to create, isolate, and manage global variables and functions separately.

const USERID_STORED = "userid_stored";
let userArray = [];
let lengthNow = 0;

function setUserArray(data) {
     userArray.push(data)
}

function getUserArray() {
     return userArray
}

function setlengthNow(data) {
     lengthNow = data
}

function getlengthNow() {
     return lengthNow
}

export {  USERID_STORED, userArray ,
        lengthNow,setUserArray, getUserArray,setlengthNow,getlengthNow }

Useage

import  {  USERID_STORED, userArray ,lengthNow,setUserArray, getUserArray,setlengthNow,getlengthNow } from "./globalfunction path"

....
setlengthNow(userArray.length) // change it here

If you do not want to lose the updated value, use AsyncStorage.

async componentDidmount() {
 const checkdata = await AsyncStorage.getItem("lengthNow");

 if(checkdata == null) {
    await AsyncStorage.setItem("lengthNow",userArray.length);
 }

}

Sign up to request clarification or add additional context in comments.

2 Comments

I think is the better way to do it thank you, but why I have to check if checkdata == null ?
This is to make sure there is data when the app is reloaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.