Search code examples
javascriptarchitecturesinatrareactjsreactjs-flux

How to connect Flux to Sinatra API


I'm using React for a web application, and I've started learning about Flux. I like the concept of a unidirectional data flow, but I'm having some problems understanding how that connects to an API.

I have a back end written in Sinatra. What I'm confused about is how does the data flow from an interaction with the component to the back end and back again? Is it that the database and what Flux calls a Store are two different things?

The way I'm interpreting it is like this:

User interacts with React View =>

Action Creator sends data to back end =>

back end responds to Action Creator with new data/success/error =>

Action Creator sends action and response to Dispatcher =>

the Dispatcher sees the action and calls the callback based on that Action, passing it the back end response =>

the Store updates itself using the back end response =>

the Store sends the change event and the data to the React View =>

the React View renders =>

(cycle repeats)

Flux flow

What confuses me is how the stores work. Do I need two stores like how I'm interpreting it? Or is the back end supposed to be the store?


Solution

  • No, you "just" have the one store - it usually helps to think about it in a one store - one component relationship. Note, this should be taken with a grain of salt since it's definitely possible to have several stores connected to one component and vice versa.

    There's a few ways you can implement backend communication but the way I normally do it is this, usually with the Reflux implementation of Flux (as I think it's more straight forward and follows roughly the same concept as a React component):

    var SomeStore = Reflux.createStore({
        getInitialState: function () {
             //called when store is created
    
             var ApiPromise = MyApi.get('/my-resource-path/');
             ApiPromise.success(function (data) {
                  this.data = data;
                  this.triggerUpdateOfComponent(this.data);
             }.bind(this));
        }
    });
    

    Using just normal Flux implementation you would do this in the Dispatcher and when the application starts loading you would trigger an action through an Action Creator and tell the Dispatcher to start doing its work.

    To help with the grokking of a store, think of it as the container that handles the logic and manipulation related to your components data.