Flux/Alt data dependency, how to handle elegantly and idiomatically

后端 未结 3 1719
猫巷女王i
猫巷女王i 2021-01-17 18:55

I\'m using alt as my flux implementation for a project and am having trouble wrapping my head around the best way to handle loading stores for two related entities. I\'m usi

相关标签:
3条回答
  • 2021-01-17 19:27

    I've been looking at @gravityplanx's answer, but am not sure how much it improves the situation.

    To reiterate and amplify: I really, really like the alt pattern of loading my stores from a source. Every component that needs a store(s) looks something like so:

    export default class extends React.Component {
        componentDidMount() {
            CurrentUser.fetch();
            Jobs.fetch(); 
        };
        render() {    
            return(
              <AltContainer stores={{user:CurrentUser, jobs:Jobs}}>
                   <Body/>
              </AltContainer>)
        }
    
    }
    

    The intent is understandable at a glance. And I get a clean separation of concerns, making it easier to test my actions/stores, and sources.

    But the beautiful pattern breaks down in the common use case from my question, and I wind up having to create some fairly complicated plumbing in my actions and stores to orchestrate the ajax calls for the conversations. The other answer seems to just shift this complexity elsewhere. I want it gone.

    What I wound up doing was to completely separate the stores (the first solution suggested in the question). I make an extra ajax call to fetch the conversationId off the job and another to fetch the conversations in the JobConversation source. Something like this:

      axios.get(window.taxFyleApi + 'api/platform/active-jobs-pick/layerConversation?jobId=' + jobId)
                .then((res)=> {
                    let job = res.data[0];  //Returns an array with only one item
                    let qBuilder = window.layer.QueryBuilder.messages().forConversation(job.conversationId)...
    

    I preserve the nice way of using AltContainer with my components and lose all the orchestration plumbing. Right now, I think the resultant clarity is worth the extra back end call.

    I also realize how I'd LIKE it to work (in terms of notation), and will ask @goatslacker about, or may take a shot at doing it myself. I'd like to be able to specify the dependency in the exportAsync() method on a store. I'd love to be able to say:

    class JobConvesationStore {
        constructor() {
            this.exportAsync(source, JobStore);
        }
    

    The async method JobConversationStore would not be called until the JobStore had its data. The intent is easy to read and no complex action choreography would be needed.

    0 讨论(0)
  • 2021-01-17 19:35

    This definitely seems like a flaw in the Flux design, and you're right, it is a very common use case. I've been researching this issue (and a few similar ones) for a few days now to better implement Flux in my own system, and while there are definitely options out there, most have drawbacks.

    The most popular solution seems to be using Containers, such as AltContainer, to abstract away the task of data requesting from apis and loading from stores into a single component, absent of ui-logic. This Container would be responsible for seeing the information from the stores and determining if additional actions are required to make them complete. For example;

    static getPropsFromStores() {
        var data = SomeStore.getState();
        if (/*test if data is incomplete */){
            SomeAction.fetchAdditionalData();
        }
        return data;
    }
    

    It makes sense. We have the logic and component in our Component layer, which is where Flux says it belongs.

    Until you consider the possibility of having two mounted containers asking for the same information (and thus duplicating any initialization fetches, i.e. conversations in your model), and the problem only gets worse if you add a third (or fourth, or fifth) container accessing those same stores.

    The canned response to that from the Container crowd is "Just don't have more than one!", which is great advice... if your requirements are ok with that.

    So here's my altered solution, around the same concept; Include one Master Container/Component around your entire application (or even beside it). Unlike traditional containers, this Master Container/Component will not pass store properties to its children. Instead, it is solely responsible for data integrity and completion.

    Here's a sample implementation;

    class JobStore {
        constructor() {
            this.bindListeners({
                handleJobUpdate: jobActions.success
            });
    
        },
    
        handleJobUpdate(jobs) {
            this.jobs = jobs;            
        }
    }
    
    class ConversationStore {
        constructor() {
            this.bindListeners({
                handleJobUpdate: jobActions.success,
                handleConversationUpdate: conversationActions.success
            });
    
        },
    
        handleJobUpdate(jobs) {
           this.conversations = {};
           this.tmpFetchInfo = jobs.conversation_id;
           this.isReady = false;
    
        },
    
        handleConversationUpdate(conversations) {
           this.conversations = conversations;
           this.tmpFetchInfo = '';
           this.isReady = true;
        }
    
    }
    
    class MasterDataContainer {
    
        static getPropsFromStores() {
            var jobData = JobStore.getState();
            var conversationData = ConversationStore.getState();
    
            if (!conversationData.isReady){
                ConversationAction.fetchConversations(conversationData.tmpFetchInfo);
            }  
        },
    
        render: function(){
            return <div></div>;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 19:45

    The best solution I've come with with so far (and the one that the examples seem to follow) is to add a "jobsFetched" action to my jobs actions and to dispatch it when the data arrives.

    var jobActions = require('../actions/Jobs');
    var ConversationActions = require('../actions/Conversations');
    
    class JobStore {
        constructor() {
            this.bindListeners({
                handlefullUpdate: jobActions.success...
            });...
    
        }
    
        handlefullUpdate(jobs) {
            this.jobs = jobs;
            ConversationActions.jobsFetched.defer(jobs);
        }
    }
    
    
    class ConversationStore {
        constructor() {
            this.bindListeners({
                handleJobUpdate: jobActions.jobsFetched...
            });...
    
        }
    
        handleJobUpdate(jobs) {
    
            /*Now kick off some other action like "fetchConversations" 
              or do the ajax call right here?*/
    
        }
    
    }
    

    This eliminates the problem of the jobs store having to hold a reference to all its dependent objects, But I still have to call an action from inside my store, and I have to introduce jobsFetched action which sets up the ConversationStore to fetch it's data. So it seems like I can't use a source for my conversations.

    Can anyone do better?

    0 讨论(0)
提交回复
热议问题