Jason Chen Jason Chen - 3 months ago 17
React JSX Question

Using React to call a variable from multiple files?

My code is arranged like so:

main.jsx

var React = require('react');
var ReactDOM = require('react-dom');
var Console = require('./console.jsx');
var Dashboard = require('./dashboard.jsx');

var datastored = new Dexie('Notes');
datastored.version(1).stores({entries:'++id, title, entry' });
datastored.open().catch(function(err){alert("Could not open database:"+err)});


This
main.jsx
boots up my database via the
datastored
variable, which uses the IndexDB wrapper Dexie.js. Now, I would like to call the
datastored
variable from my other files (such as
console.jsx
or
dashboard.jsx
).

In my particular instance, I have a
<Addnote/>
inside
<Dashboard/>
. Inside
<Addnote/>
I have this function.

addnote.jsx

sendthru:function(){
var newInput = {
title: this.inputTitle.value,
entry: this.inputEntry.value
};
datastored.entries.add(newInput).then(()=>this.runcheck());
this.inputTitle.value = '';
this.inputEntry.value = '';
},


When
sendthru
is launched, however, my console error states that
datastored is not defined
. So I'm wondering how I would enable my entire app to make calls to the
datastored
variable.

Answer

You could store your data in another module. Modules are singletons, so you could create your own file (say, storage.js) and inside of it export an object with fields you would like to make available to the rest of your code. Then when you require('./storage') you will have access to that same data everywhere else.

Comments