piotrwitek / typesafe-actions

Typesafe utilities for "action-creators" in Redux / Flux Architecture
https://codesandbox.io/s/github/piotrwitek/typesafe-actions/tree/master/codesandbox
MIT License
2.41k stars 98 forks source link

Generic actions #41

Closed abdurahmanus closed 6 years ago

abdurahmanus commented 6 years ago

Hello, I have a set of actions and reducers which I want to reuse in several places in my app. I want to store similar data which generates with those actions and reducers in different places of redux store, so I need to parametrize somehow actions and reducers, for example, to add some prefix to all actions names in a set. Is it a good and possible idea? Or should I use some data in action's payload to differentiate actions?

piotrwitek commented 6 years ago

Hi, I would need more context to understand your solution. Could you please provide code examples with brief explanation for each of them

abdurahmanus commented 6 years ago

https://codesandbox.io/s/ympvlp0qnz

see src/features/test1 folder I have 2 use cases: 1) actions1, reducer1 async actions, shape of actions the same, but request and result types are different (number, Data1[] and string Data[2]). reducers logic identical, store only differentiates in types of data 2) set of actions (actions2, reducer2) I want to store data with identical shape in several parts of my app's store. To achive this. i have to duplicate actions (with different prefixes in action types) and duplicate logic in reducers.

How can I improve my code in order to avoid so many duplications P.S. sorry for my English)

piotrwitek commented 6 years ago

Ad 1) Seems like a parametrized factory function that will generate an action creators and generic reducer pairs could work for such case. I don't have an example but you can find some examples for JS on the internet and use typesafe-actions inside the factory and use type inference to return typesafe actions/reducers.

Ad 2) If actions payload is the same and reducer logic is the same, I would probably use meta data to differentiate when to update state in each part.

abdurahmanus commented 6 years ago

image I was trying to do it this way, but string concat results to incorect actions type (string instead of 'something/action1', 'something/action2'). I'm very new to typescript. Should I use type params? What if I have to produce many actions? In this case the list of params will be long.

piotrwitek commented 6 years ago

You always have to provide entire string literal, it's "static-types" so they are static by definition, and you're trying to make them dynamic, which is impossible

piotrwitek commented 6 years ago

Not actionable, closing.

pushys commented 4 years ago

Given the recent huge TypeScript update, I guess dynamic action types have become very possible now.