Problem
I want to have a global counter in react native to show how many notifications a user has in an app that I am creating.
I created a global variabal in a file named global.js:
var notifNum = 0;
global.n = notifNum;
then in my code, I import it with
import './global.js'
then later I try to update it with
global.n = notifNum;
Notif num being the number of notifications a user has, defined in a function. The problem is that global.n
stays as 0, and doesn't change at all.
How can I edit the global.n variable?
Problem
I want to have a global counter in react native to show how many notifications a user has in an app that I am creating.
I created a global variabal in a file named global.js:
var notifNum = 0;
global.n = notifNum;
then in my code, I import it with
import './global.js'
then later I try to update it with
global.n = notifNum;
Notif num being the number of notifications a user has, defined in a function. The problem is that global.n
stays as 0, and doesn't change at all.
How can I edit the global.n variable?
Share Improve this question asked Jan 10, 2018 at 2:00 user8749566user87495662 Answers
Reset to default 2There is one hacky way to modify a global.foo
variable.
Doesn't work
global.foo = 'foo'; //this cant be changed
global.foo = 'foofoo';
console.log(global.foo); //foo
Does work
global.foo = ['foo']; //this can be changed
global.foo[0] = 'foofoo';
console.log(global.foo[0]); //foofoo
This has less to do with React-Native and more to do with how javascript works as a language.
In short, you must export
what you wish to use in other files.
Global.js
let counter = 0;
const increment = () => {
counter++;
console.log('counter_updated', counter);
};
const worker = {
increment,
counter
};
module.exports = worker;
We've told the JS engine exactly what we want to import in other files. Assigning it to and object and exporting the object is not necessary but allows for cleaner imports/exports IMO.
Component.js
import { counter, increment } from 'pathTo/global';
We deconstruct the object we exported and are now able to modify/use values in the global.js file.
Food for thought
This is not an ideal solution as it is not two ways. Incrementing the count in the global.js
file will not update the value in the ponent.js
.
This is because React needs to have it's state updated to initiate a re-render
of a ponent.
Also, this will not persist through app reloads, which I believe you would want for something such as notifications.
Other solutions
- Storing the notification counts in a database.
- Using ponent
state
to manage the count. - Using a state manager like
Redux
orMobX