2

Maybe someone has had a similar situation and can help with this:

Very simplistic view:

  • I have a Vuex module that I am using with two different stores
  • This module uses a "normalizer" function that maps data from an API into the format that's used by the components consuming the data
  • The components in the two stores need the data in slightly different formats
  • My current idea is to have two different "normalizer" functions that share the same "interface" but produce slightly different outcomes, and "inject" them as a dependency into the module before attaching it to the store:

Existing code - "fixed" normalizer function (plain old Vuex module):

// module.js
import { normalize } from './utils';

const actions = {
    getData({ commit }) {
        MyApi.getData().then((data) => {
            commit('setData', data.map(normalize));
        });
    },
};

// ...
export default {
    actions,
    // ...
}
// my-store.js
import MyModule from './my-module';

export default new Vuex.Store({
    modules: {
        'my-module': MyModule,
    },
    // ...
});

New code that can accept different functions:

// module.js

export default (inject) => {
    const { normalize } = inject;

    const actions = {
        getData({ commit }) {
            MyApi.getData().then((data) => {
                commit('setData', data.map(normalize));
            });
        },
    };
    //...
    return {
        actions,
        // ...
    };
}
// store-type-1.js
import getMyModule from './my-module';
import normalizerType1 from './normalizer-type-1';

export default new Vuex.Store({
    modules: {
        'my-module': getMyModule({ normalize: normalizerType1 }),
    },
    // ...
})

Thing is, something about this implementation feels like a sore thumb, and I'm pretty sure there are smarter ways of doing this, I'm just not smart enough to think of them.

I can provide more details about what this "normalizer" function is expected to do, maybe I'm barking up the wrong tree.

What's the industry standard for this sort of thing?

Thank you!

2
  • Seems fine. I guess the question is do you really need dynamic modules? Maybe that's what feels off to you. Because it might feel more appropriate to do this data management with a simple function inside a single store and use multiple state/actions instead of multiple modules. Might be overkill. Commented Feb 24, 2020 at 12:26
  • @Dan thanks for the feedback. One of the uses of this "normalizer" function is to determine the component used to render each particular entry. I thought I needed multiple functions to enable me to use multiple templates. Commented Feb 24, 2020 at 19:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.