4

How do I maintain a central/global object for some data with react-router?

Let's say my React site has 20 different routes. 15 out of those 20 routes need one JSON file from the server that almost never changes. I hate having to GET "/api/mydata" for every new URL/route.

I guess I can save the data in React's context, but that seems hacky and may not even work. Is there a more elegant solution for sharing data between react-router components?

Edit: I partially solved this by creating a Data.js file:

export var myData = function(cb) {
  ajax('GET', '/api/mydata', resp => {
    myData = function() {
      return cb(resp);
    };
    cb(resp);
  });
};

and use it like this:

myData(data => data.map(/* ...use the data */));

That way the data is guaranteed to only be fetched once per lifecycle.

3
  • 1
    You can just store those data as a props in the root component and pass it to the child component. Routing in react-router will not reset the props. I suggest you to learn react-redux or flux, they solved your problem.
    – Kit Fung
    Commented Dec 10, 2015 at 10:47
  • I've come across redux and flux and vaguely understood that this is the problem they solve, but I was too worried about adding more KB's to my program
    – zelcon
    Commented Dec 10, 2015 at 11:32
  • Redux is ~2kb. I don't think you should worry about that sort of things.
    – charlespwd
    Commented Dec 10, 2015 at 12:37

1 Answer 1

3

Arrr... if you don't want to use redux or flux, you can create a singleton like this in a new js file

let appState = {};
export default appState;

First do ajax to fill the data into this singleton. Then import it to everywhere you want the data.

1
  • Tried too long to get this to work...I'll just use redux in the future. For this project, I'll just play with the cache-control headers to keep things streamlined.
    – zelcon
    Commented Dec 11, 2015 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.