Pisze front w React Reflux i mam pytanie czy ktoś z Was łączył się kiedyś z webApi, nie jestem pewien jak to dokładnie powinno wyglądać (a jak wiadomo obecnie każdy tutorial z reacta wygląda inaczej z racji czestych zmian). Prosze o rady, poniżej kod:
login.jsx
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
//getInitialState() { return {}; }
logIn(e) {
var detail = {};
Array.prototype.forEach.call(
e.target.querySelectorAll('input'),
function(v) {
detail[v.getAttribute('name')] = v.value;
});
e.preventDefault();
e.stopPropagation();
Actions.login(detail.login, detail.password)
.then(function() {
//console.log("SUCCESS", arguments);
this.history.pushState('', '/');
}.bind(this))['catch'](function() {
//console.log("ERROR", arguments);
this.setState({
'loginError': 'bad username or password'
});
}.bind(this));
}
render () {
return (
...TODO....
);
}
}
export default LoginPage
actions.js
import Reflux from 'reflux';
export default Reflux.createActions({
'getMenu': {
asyncResult: true
},
'login': {
asyncResult: true
},
'logOut': {},
'search': {},
'getSessionContext': {}
});
appConfig:
export default {
pageSize: 6,
apiRoot: '//localhost:3000',
postSummaryLength: 512,
loadTimeSimMs: 2000
};
context.js:
import Reflux from 'reflux';
import Actions from 'appRoot/actions';
import Request from 'superagent';
import Config from 'config/appConfig';
import Cookie from 'appRoot/vendor/cookie';
export default Reflux.createStore({
listenables: Actions,
endpoint: Config.apiRoot + '/users',
context: {
loggedIn: false
},
getInitialState: function() {
this.context = JSON.parse(Cookie.getItem('session')) || {};
this.context.loggedIn = this.context.loggedIn || false;
return this.context;
},
getResponseResolver: function(action) {
return function(err, res) {
if (res.ok && res.body instanceof Array && res.body.length > 0) {
this.context = res.body[0];
this.context.loggedIn = true;
this.context.profileImageData = null;
this.trigger(this.context);
action.completed();
Cookie.setItem('session', JSON.stringify(this.context));
} else {
action.failed();
}
}.bind(this);
},
getSessionInfo: function() {
return JSON.parse(Cookie.getItem('session'));
},
onLogin: function(name, pass) {
Request
.get(this.endpoint)
.query({
'login': name,
'password': pass
})
.end(this.getResponseResolver(Actions.login));
},
onLogOut: function() {
Cookie.removeItem('session');
this.context = {
loggedIn: false
};
this.trigger(this.context);
return true;
}
});