elsassph / haxe-redux

Haxe Redux externs and support classes for a smarter API
8 stars 2 forks source link

Generic action/state/reducer #22

Open zabojad opened 5 years ago

zabojad commented 5 years ago

I'm wondering how to achieve generic actions/states/reducers with this lib...

The idea is to define some "generic feature redux brics" like for example an entity list redux bric.

I've tried something like this:

Generic stuff:

typedef Entity = {
  id:Int
}

enum EntityListPageAction<E:Entity> {
    Reset;
    RequestListEntities(from:Int);
    ReceiveListEntities(r:Array<E>, tc:Int, from:Int);
}

typedef EntityListPageState = {
    isLoading:Bool,
    list:Array<EntityKey>,
    totalCount:Int
}

class EntityListPageRdcr<E:Entity,A:EntityListPageAction<E>> implements IReducer<A, EntityListPageState> {
    public function new() {}

    public var initState:EntityListPageState = {
        isLoading: false,
        list: null,
        totalCount: 0
    };

    public function reduce(state:EntityListPageState, action:EntityListPageAction<E>):EntityListPageState {
        var partial:Partial<EntityListPageState> = switch (action) {
            case Reset:
                initState;

            case RequestListEntities(o):
                var r:Array<EntityKey> = o == 0 ? null : state.list;
                var cnt:Int = o == 0 ? 0 : state.totalCount;
                {isLoading: true, list: r, totalCount: cnt};

            case ReceiveListEntities(r, cnt, o):
                var ctr:Array<EntityKey> = state.list != null && o > 0 ? state.list : [];
                ctr = ctr.concat([for (rr in r) rr.id]);
                {list: ctr, totalCount: cnt, isLoading: false};
        }

        return (state == partial ? state : Object.assign({}, state, partial));
    }
}

and a use of it:

typedef TypeRecipesPageAction = magimix.state.generic.EntityListPageState.EntityListPageAction<magimix.dto.Recipe>;

typedef TypeRecipesPageState = EntityListPageState;

typedef TypeRecipesPageRdcr = EntityListPageRdcr<magimix.dto.Recipe,magimix.action.TypeRecipesPageAction>;

It doesn't compile with errors I do not really understand as it reaches my knowledge limits about haxe macros used in this lib implementation.

So, before losing more time trying to make it work probably in vain, I'd prefer ask the question here. Would haxe-redux allow such definition of action/state/reducer ?

If yes, what do I do wrong?

If no, would that be a lot of work to add it to the lib?

Thanks in advance for your answers...

kLabz commented 5 years ago

Can you post the errors and/or a reduced example/project that we can try to compile?

elsassph commented 5 years ago

There are no macros involved in this part of the code:

I'm not sure enums really work with generics here. I tried that: https://try.haxe.org/#E2483

I guess it could somehow work, but not the way you expect.