My Api is just a plain old javascript object (POJO) like this. It's in ES6 but you should get the idea:
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
}
};
Then, I call it in my Store like so:
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);
}
});
I don't update my store and this.trigger()
until the api call returns.
A smarter idea might be to optimistically update:
// inside the todo store
onCreate(todo) {
Api.create(todo);
this.update([todos].concat(this.todos));
},
update(todos) {
this.todos = todos;
this.trigger(todos);
}
Obviously, this is one way to do it, but it's certainly not the only way.
But, the main idea is the Store uses the API.
The API is not part of the data flow of:
Action->Store->Component->Action etc.