Home > OS >  Sharing varible data between components in React
Sharing varible data between components in React

Time:10-20

I have made a touch typing game in React and Node.js and I want to have the function component from the TypeScript page update a globally shared EXP variable so that players can navigate around the app pages and keep their earned XP. The variable can reset once they close the app, it just needs to be per session. Here is a bit of the code for the XP inside type.tsx which is a function component called in the routes in App.js

Type.tsx

...

if (currIndex   1 === length) {
      xpM = xpM   1;
      bonusCounter = bonusCounter   1;
      err = err   errorChar;
      currXP = xp * correctChar;
      addXP = (currXP - (err * 2)) * xpM;
      xpPercent = Math.round((uXP/xpNeed) * 100);
      (gain as HTMLAudioElement).play();
      console.log(xpPercent);
      if (err > correctChar) {
        addXP = correctChar * 3;
      }
      tXP = tXP   addXP;
      uXP = tXP;
...

I want the tXP, xpNeed, and level variables to be accessable from the Select Test component as well as the other typing pages (there are 6 different tests with different text arrays to populate the typing text.) I have read that Redux could do this but after looking into it it seems I would need to rebuidld the entire app to use Redux tools. Is there a quick and dirty way to achieve this? The app is only being used as a demo for a larger Unity game that is in development so it doesn't have to be a super elegant or complex solution. Thanks!

CodePudding user response:

This question is likely to be closed due to answers being opinionated which is not suited for SO.

However... I recommend you use React Context to share the state between your components. You can create an EXP variable that can be accessed from your relevant components and share updates.

If you need to keep a server in sync, you can post the EXP increments when you update local state in the Context Provider above, or use socket.io if you need realtime comms and the game is very chatty.

CodePudding user response:

Create a class for global variables and its methods:

export default class GlobalVariables {
static createVariables() {
    //set here variables you want to be global
    this.tXP = 0;
}

static getXP() {//method to get XP
    return this.tXP;
}

static addXP(value) {//method to add XP
    this.tXP  = value;
}

//create others methods you want for your variables
}

In your start component import the class and call createVariables (call this when the app starts):

import GlobalVariables from './Global'
...
GlobalVariables.createVariables()
...

In your others components import the class and use the others methods:

import GlobalVariables from './Global'
...
GlobalVariables.addXP(5);
console.log(GlobalVariables.getXP())
...
  • Related