私の Api は、このような単純な古い JavaScript オブジェクト (POJO) です。それはES6にありますが、アイデアを得る必要があります:
import request from 'superagent';
// Other helpers functions and setup
let handle = (err) => {
// error handling stuff
};
export default {
create(user, cb) {
return request
.post(server + '/api/users/new')
.send(user)
.on('error', (err) => {
handle(err);
cb(err);
})
.end(cb);
},
login(user, cb) {
// Post some more stuff
}
};
次に、ストアで次のように呼び出します。
import Reflux from 'reflux';
import UserActions from '../actions/UserActions';
import Api from '../api/UserApi';
const UserStore = Reflux.createStore({
listenables: [UserActions],
getInitialState() {
// insert stuff
},
onCreate(user) {
Api.create(user, (err, res) => {
if (err) {
console.log(err);
} else {
// Do something with res
// this is for JSON, your API might be different
let user = JSON.parse(res.text);
this.update(user);
}
})
},
onLogin(user) {
// login stuff
},
// More methods
update(user) {
this.currentUser = user;
this.trigger(user);
}
});
this.trigger()
API呼び出しが戻るまで、ストアを更新しません。
より賢明なアイデアは、楽観的に更新することです。
// inside the todo store
onCreate(todo) {
Api.create(todo);
this.update([todos].concat(this.todos));
},
update(todos) {
this.todos = todos;
this.trigger(todos);
}
明らかに、これはそれを行う 1 つの方法ですが、これが唯一の方法ではないことは確かです。
ただし、主なアイデアは、Store が API を使用することです。
API は、次のデータ フローの一部ではありません。
アクション -> ストア -> コンポーネント -> アクションなど。