aikoven / typescript-fsa-redux-saga

TypeScript FSA utilities for redux-saga
MIT License
61 stars 4 forks source link

Provide a real world example please #1

Open Razinsky opened 7 years ago

Razinsky commented 7 years ago

Could you provide a real world example of using typescript-fsa with redux-saga?

I'd like to see how you dispatch and take a typescript-fsa action in a saga.

Thanks!

aikoven commented 7 years ago

Sure!

Dispatching is as easy as:

const myAction = actionCreator<foo: string>('MY_ACTION');

function* saga() {
  yield put(myAction({foo: 'bar'}));
}

As for takeing, action creators produced by typescript-fsa have additional property type attached to them, which corresponds to the type of created actions. You can use it to wait for a specific action:

function* saga() {
  const action = yield take(myAction.type);
}

Note that unfortunately, TypeScript is currently unable to infer the type of value returned from yield, so it's a good practice to always annotate types in this case:

import {Action} from "typescript-fsa";
// ...
const action: Action<{foo: string}> = yield take(myAction.type);

Also, once redux-saga@0.15.0 gets released, we could use this feature to simplify things a bit and just write

yield take(myAction);

The last note, you don't need this package (typescript-fsa-redux-saga) for the things described above. It currently only contains a helper for wrapping async workers with AsyncActionCreators.

ThomasStock commented 7 years ago

How do you dispatch an async action from a connect'ed component? The syntax seems to differ from dispatching a sync action, exposing to components that this is an async action? I would like to hide this action being an async action from my components.

I already have this running: yield takeEvery(likeAsset.type, likeAssetWorker)

and want to "trigger" this from my component. I'm used to doing this:

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onLike: () => dispatch(likeAsset({id: ownProps.asset.id, like: true})),
    }
}

But after switching to typescript-fsa I get the error: _Uncaught TypeError: (0 , assetactions.likeAsset) is not a function

aikoven commented 7 years ago

Sorry for the late reply.

Async actions are not meant to trigger an async process, but rather wrap it so that you could handle its lifecycle events.

Please see this discussion: https://github.com/aikoven/typescript-fsa/issues/29