score:1
it will make your app easier to build and maintain if you include the flux pattern. i suggest you take a look at some of the starter projects and pick one that compliments your own style. here is an example from https://github.com/calitek/reactpatterns react.14/refluxsuperagent. it may seem complex but the pattern offers a good separation of concerns and flexibility.
server.js
'use strict';
let bodyparser = require('body-parser');
let express = require('express');
let favicon = require('serve-favicon');
let path = require('path');
let port = number(3500);
let routes = require('./routes');
let app = express();
let server = app.listen(port);
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/', express.static('ui-dist'));
app.use('/routes', routes);
app.use(favicon(path.join(__dirname, '..', 'ui-dist', 'img', 'favicon.ico')));
app.get('/', function(req, res){ res.sendfile(__dirname + '/index.html', [], null); });
'use strict';
let express = require('express');
let router = express.router();
let getsetdata = require('./routes/getsetdata');
router.get('/getdata', function(req, res) {
let getdatadone = function(data){ res.send(data); };
getsetdata.getdata(getdatadone);
});
router.post('/setdata', function(req, res) {
let setdatadone = function(data){ res.send(data); };
console.log(req.body);
getsetdata.setdata(req.body, setdatadone);
});
module.exports = router;
getsetdata.js
'use strict';
var fs = require('fs');
var rootdatapath = './data';
var getdata = function(donecallback) {
var filepath = rootdatapath + '/basic.json';
var jsonreadcallback = function(err, data){
if (err) donecallback('data readfile error ' + filepath);
else {
var jsondata = json.parse(data.tostring());
donecallback(jsondata);
}
};
fs.readfile(filepath, jsonreadcallback);
};
var setdata = function(data, donecallback) {
var filepath = rootdatapath + '/basic.json';
var writefilecallback = function (err) {
if (err) console.log('error saving data.json file ');
donecallback('ok');
};
fs.writefile(filepath, json.stringify(data, null, 2), writefilecallback);
};
module.exports.getdata = getdata;
module.exports.setdata = setdata;
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>reactpatterns-refluxwebsocket</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css">
<link rel="stylesheet" href="app.min.css"/>
</head>
<body class="bodystyle main">
<header class="text-center header" >
<span class="title">reactpatterns-refluxsuperagent by janaka</span>
</header>
<section id="react" class="content"></section>
<script src="app.min.js"></script>
</body>
</html>
app.js
'use strict';
import react from 'react';
import reactdom from 'react-dom';
import appctrl from './components/app.ctrl.js';
import actions from './flux/actions';
import apistore from './flux/api.store';
window.reactdom = reactdom;
actions.apiinit();
reactdom.render( <appctrl />, document.getelementbyid('react') );
api.store.js
import reflux from 'reflux';
import actions from './actions';
import apifct from './../utils/api.js';
let apistoreobject = {
newdata: {
"react version": "0.14",
"project": "refluxsuperagent",
"currentdatetime": new date().tolocalestring()
},
listenables: actions,
apiinit() { apifct.setdata(this.newdata); },
apiinitdone() { apifct.getdata(); },
apisetdata(data) { apifct.setdata(data); }
}
const apistore = reflux.createstore(apistoreobject);
export default apistore;
api.js
import request from 'superagent';
import actions from '../flux/actions';
let uri = 'http://localhost:3500';
module.exports = {
getdata() { request.get(uri + '/routes/getdata').end((err, res) => { this.gotdata(res.body); }); },
gotdata(data) { actions.gotdata1(data); actions.gotdata2(data); actions.gotdata3(data); },
setdata(data) { request.post('/routes/setdata').send(data).end((err, res) => { actions.apiinitdone(); }) },
};
basic.store.js
import reflux from 'reflux';
import actions from './actions';
import addonstore from './addon.store';
import mixinstoreobject from './mixin.store';
function _gotdata(data) { this.data1 = data; basicstore.trigger('data1'); }
let basicstoreobject = {
init() { this.listento(addonstore, this.onaddontrigger); },
data1: {},
listenables: actions,
mixins: [mixinstoreobject],
ongotdata1: _gotdata,
onaddontrigger() { basicstore.trigger('data2'); },
getdata1() { return this.data1; },
getdata2() { return addonstore.data2; },
getdata3() { return this.data3; }
}
const basicstore = reflux.createstore(basicstoreobject);
export default basicstore;
app.ctrl.js
import react from 'react';
import basicstore from './../flux/basic.store';
let appctrlsty = {
height: '100%',
padding: '0 10px 0 0'
}
const getstate = () => {
return {
data1: basicstore.getdata1(),
data2: basicstore.getdata2(),
data3: basicstore.getdata3()
};
};
class appctrlrender extends react.component {
render() {
let data1 = json.stringify(this.state.data1, null, 2);
let data2 = json.stringify(this.state.data2, null, 2);
let data3 = json.stringify(this.state.data3, null, 2);
return (
<div id='appctrlsty' style={appctrlsty}>
react 1.4 reflux with superagent<br/><br/>
data1: {data1}<br/><br/>
data2: {data2}<br/><br/>
data3: {data3}<br/><br/>
</div>
);
}
}
export default class appctrl extends appctrlrender {
constructor() {
super();
this.state = getstate();
}
componentdidmount() { this.unsubscribe = basicstore.listen(this.storedidchange.bind(this)); }
componentwillunmount() { this.unsubscribe(); }
storedidchange(id) {
switch (id) {
case 'data1': this.setstate({data1: basicstore.getdata1()}); break;
case 'data2': this.setstate({data2: basicstore.getdata2()}); break;
case 'data3': this.setstate({data3: basicstore.getdata3()}); break;
default: this.setstate(getstate());
}
}
}
Source: stackoverflow.com
Related Query
- Single page app with REST API architecture
- Navigation in a single page app with react.js
- Serving a static html page from a single page react app with react router
- Symfony 4 how to setup SPA ( single page app ) with React?
- Deploying React App with Spring Boot REST API in AWS BeanStalk
- ReactJS App with REST API data is not displaying data correctly
- Unable to make api calls from React Single Page app
- React Single Page app with browserHistory possible?
- Adding underline to current page section in single page react app with Chakra.ui
- Single page application with HttpOnly cookie-based authentication and session management
- Does React.js require app to be a single page
- How to integrate azure ad into a react web app that consumes a REST API in azure too
- CORS error while consuming calling REST API with React
- CORS Issue with React app and Laravel API
- structure of a Backbone and React single page app
- React app using API with another origin (CORS)
- Pass prop to every single page in Next.js with getInitialProps using Typescript
- How to secure my react app api with csurf?
- How to implement the OAuth2 Authorization code grant with PKCE for a React single page application?
- Serving up a single page rect app using java vert.x web server
- Update "service-worker.js" on Single Page App when changing routes
- react-router throwing 404 upon page refresh with React app hosted on GoDaddy
- Next.js context provider wrapping App component with page specific layout component giving undefined data
- API route not found in a Next.js App (The page could not be found)
- Enable single page app react hot reload webpack
- React router - pass api data to the linked component to open with a new page
- React.js with Node.js Rest API
- React app showing page with "404 the requested path could not be found" when using Apache
- Next Js combined with an external REST API Authentication and atuhorization
- How to do a REST API post request with FileUpload to an Azure AD Protected REST API
More Query from same tag
- How to Position a React Native Button at the bottom of my screen to work on multiple ios devices
- Failed to compile ./src/App.js Module not found: Can't resolve 'firebase'
- How to GET image in reactjs from api?
- Editing CSS shadow part of an ionic select text (color) without affecting other instance of ion select
- How to add linking images to ckeditor in React?
- How to correctly pass State to a different function in React?
- How would I add stack tracing to my current Redux Devtools setup?
- How do I POST form data using Fetch and React?
- CSS-Module classes are undefined while React server side rendering
- React serve -s build, The term 'serve' is not recognized as the name of a cmdlet
- best way to show a header in map function if condition different to previous item
- Saving state from child component by pressing a button in parent component?
- Load assets accompanying a Javascript from a remote location
- Filter the array of objects with optional values
- one onChange input, wrongly modifies other three tags content
- Is it possible to bind inner Div Click to Outer Div?
- Passing a hook as a prop
- React - Handling Null values passed as props
- Function component doesn't re-render after updating array state in react
- Error: Uncaught [Error: Passed an incorrect argument to a color function, please pass a string representation of a color
- How to change style of an element in React without using querySelector?
- How to access to row if cell is clicked in React/Redux
- How do you use useMutation from react-apollo-hook to execute a delete mutation?
- Importing function from other file which uses redux connect function
- How to Access forLoop data outside the scope
- Update the state of an object element in React
- Formik and Material-UI
- React Material UI Insert and delete row
- CSS: Card jumps up when keyboard is enabled in mobile screen
- Expansion Panel with Text Field input change the panel's back color on input focus