monokh
monokh

Reputation: 1990

Javascript modules and application wide data

I'm confused when writing javascript modules, where and how to store data that can be used application wide.

Say i have a module that fetches some much needed data from the server. Lets say it's configuration data.

getData.js

function getData() {
    return fetch('http://data.com/my-data')
    .then(response => response.json())
}

export default getData; // Returns a promise

The app is a react app that needs to render some components but which will at an undefined point use our data.

app.js

import getData from 'getData.js';

getData.then((data) => {
    render( <TheBestApp />, document.getElementById(‘root') );
});

At some point in the hierarchy of <TheBestApp /> the data will be used.

What is the best way to get data to be available to all of our app here? These are the 2 options i see:

  1. Somehow pass the data through every component in the hierarchy (seems messy)
  2. Store the data in the global object and then render the app but i've heard to avoid the global scope

Any other ways? What is the best practice for this?

Upvotes: 1

Views: 57

Answers (2)

SethWhite
SethWhite

Reputation: 1977

I'll answer the "any other ways" part of your question, because I'm not sure if it's best practice especially not in a ReactJS environment (which I have no experience in).

Now that you have no faith in my answer:

In AngularJS, this is where I'd use a Service, which is essentially a singleton as far as data is concerned. You can emulate this in ES6 with a static function on a class.

Example:

export default class DataService {
  static getData() {
    if(this.data) {
      return Promise.resolve(this.data);//keeps function calls consistent
    }
    return new Promise(() => {
      fetch('http://data.com/my-data')
      .then(response => {
        response.json()
      })
      .then((data) => {
        this.data = data;
        resolve(data);
      })
    }
  }
}

This would then be imported and called with DataService.getData(). If you don't have the data present, it'll fetch it, else it'll just give it to you right away.

Upvotes: 1

ZekeDroid
ZekeDroid

Reputation: 7209

React does not handle application data. For such functionality, a widely used library is Redux, which has a sister library called react-redux that makes interacting between your components and your app level data very easy.

I recommend starting there as attempting to use internal state for this sort of data can be a hassle; ie. you may start passing data up and down components that don't have a need for it.

Upvotes: 1

Related Questions