Mikko Kettunen
Mikko Kettunen

Reputation: 43

React Native, how to use state from other file?

I'm making a simple drinking game. When a playing card shows, it's corresponding rule shows below it. All logic to this is in my game.js file. I have another screen, where you can read the rules, and modify them. How can I share the state between two files, so when I modify the rules in the settings.js file, the state would also change in the game.js file? The logic in settings file:

constructor(props) {
  super(props);
  this.state = {
    rule1: 'some rule1',
    ...
    rule13: 'some rule13'

    (Also TextInput fields and functions to update the state for each rule)

The logic in my game.js file for the rules right now is:

 get rules() {
 switch (deck1.deck[this.state.card]) {
 case "Ace_of_Spades":
    return <Text> some rule1 <Text>
 ...
 case "King_of_Spades":
     return <Text> some rule13 <Text>

But I would like to it have the state from the settings.js file for example like this:

get rules() {
 switch (deck1.deck[this.state.card]) {
 case "Ace_of_Spades":
    return {this.state.rule1}
 ...
 case "King_of_Spades":
     return {this.state.rule13}

So what would be the easiest and simplest method to just share these states between the 2 files?

Upvotes: 1

Views: 996

Answers (3)

Prashanth M
Prashanth M

Reputation: 326

You can use a global state management system like MobX or Redux. Any change to the store it will trigger an update in all files where the store is called.

Using AsyncStorage is another option but it will soon get messy.

Upvotes: 0

Aamir
Aamir

Reputation: 493

Storing settings seems like the perfect use-case for AsyncStorage. Expo, which it seems you are using, has a tutorial on it.

In your settings.js file, you'd want to call AsyncStorage.setItem() whenever one of the rules gets changed. In your game.js file, you'd want to call AsyncStorage.getItem() to access the rule you want.

Be aware that AsyncStorage from react-native is deprecated, but Expo recommends to keep using it

Upvotes: 1

nipuna-g
nipuna-g

Reputation: 6652

The way that this problem is usually handled in React is by lifting the state up.

So in your example, the games settings should be lifted up to a scope where it can be accessed both by the games.js and the settings.js components. This ensures that the data flow is always one way and that when you need to share this same state with a new component, you can do so easily.

So what would be the easiest and simplest method to just share these states between the 2 files?

The easiest way would be to keep the state in the parent game component and pass down methods to change this state to the settings component - you can follow this answer on how to do that: https://stackoverflow.com/a/35537718/3156644

But if you are going to be sharing the state with multiple components, you should be looking at React Context or a state management tool such as Redux.

Upvotes: 0

Related Questions