0

I am refractoring an app I've build using React.js. I am exporting a variable from the global scope of Spotify.js and importing it in two other files App.js and Button.js. After calling a function from Spotify.js that sotres a new value to the variable, It's new value is exported to 'Button.js' but stays an empty string in 'App.js'.

Your help would be appriciated :)


export let userAccessToken = '';
export const Spotify = {
  ...
  getUserAccessToken (){
    //stores a new string to userAccessToken.
    }
  }
  import {userAccessToken, Spotify} from '../../util/Spotify';

  export class App extends React.Component {
    //a conditional rendering happens depending on if(!userAccessToken)
  }
  import {userAccessToken, Spotify} from '../../util/Spotify'

  export class Button extends React.Component {

      componentDidMount() {

      if (!userAccessToken) {

        console.log(`Button's UAT before calling the fn: ${userAccessToken}`)
        Spotify.getUserAccessToken();
        console.log(`Button's UAT after calling the fn: ${userAccessToken}`);

      } 
    }

  ...

  }

3 Answers3

0

This is not how you share data between react components.

Use react context or pass props between components

You could use react context to share data or simply pass it as props (if the components are closely related in the component tree)

Jørgen
  • 134
  • 10
  • Hey Jørgen, Thanks for your replay :) I context and props are used to pass information in a downwards flow between react components but (what I failed to mention was..) I am looking for a way to pass information from a utility file `Spotify.js` to a react component `App.js`. As I mentioned above this seems to work with a different componenet, `Button.js`. Should I link my repo? – Yariv Shamash Jul 17 '19 at 15:42
  • Thanks for your time and support :) – Yariv Shamash Jul 22 '19 at 13:40
0

The only thing I can recommend is to export the userAccessToken, something like this, but you can't change its value outside the module

export const Spotify = {
  ...
  getUserAccessToken (){
    //stores a new string to userAccessToken.
    }
  }
  ...
}

const accessToken = Spotify.getUserAccessToken();
export const userAccessToken = accessToken;
0

If you got to read this question I solved it. Turns out I should have called my method Spotify.getUserAccessToken() from App.js using the react lifecycle method componentDidMount(). The export and import methods are like snapshots of the module and therefore when I exported the variable userAccessToke from Spotify.js before calling the my method I imported an empty string and it did not update in all files.

Thanks Jørgen and joseluismurillorios for your support and time spent answering :)