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

Async-flow with params #62

Closed 0FilipK closed 6 years ago

0FilipK commented 6 years ago

Hello, I'm trying to make an API call with params but I achieved only empty API call for now. Here is code:

Actions:

import { createAsyncAction } from 'typesafe-actions';
import {ICats} from '/api/cats';

export const FETCH_CATS_REQUEST = 'cats/FETCH_CATS_REQUEST';
export const FETCH_CATS_SUCCESS = 'cats/FETCH_CATS_SUCCESS';
export const FETCH_CATS_ERROR = 'cats/FETCH_CATS_ERROR';

export const fetchCats = createAsyncAction(
    FETCH_CATS_REQUEST,
    FETCH_CATS_SUCCESS,
    FETCH_CATS_ERROR
) <void, ICats, Error> ();

Call dispatch:

store.dispatch(fetchCats.request());

My epics:

const fetchCatsFlow: Epic<Types.RootAction, Types.RootAction, Types.RootState> = (action$) =>
    action$.pipe(
        filter(isActionOf(fetchCats.request)),
        switchMap(() =>
            fromPromise(Cats.getDataFromAPI()).pipe(
                map(fetchCats.success),
                catchError(pipe(fetchCats.failure, of))
            )
        )
    );

API:

export const Cats = {
    getDataFromAPI: () => $http.get('/cats').then(res => {
        return res.data as any;
    }),
};

I tried to call dispatch like this: store.dispatch(fetchCats.request(data)); but request expects 0 params. And like this: store.dispatch({ type: fetchCats.request(), data});

Probably I should do something like this:

const fetchCatsFlow: Epic<Types.RootAction, Types.RootAction, Types.RootState> = (action$) =>
    action$.pipe(
        filter(isActionOf(fetchCats.request)),
        switchMap((params) =>
            fromPromise(Cats.getDataFromAPI(params)).pipe(
                map(fetchCats.success),
                catchError(pipe(fetchCats.failure, of))
            )
        )
    );
export const Cats = {
    getDataFromAPI: (params) => $http.get('/cats', {
params: {
type: params.type
}
}).then(res => {
        return res.data as any;
    }),
};

but I don't know how to transform this actions properly. In docs: https://github.com/piotrwitek/typesafe-actions#--the-async-flow there is no such an example with passing params.

piotrwitek commented 6 years ago

Hello, I'm trying to make an API call with params but I achieved only empty API call for now. Here is code:

You defined request type as empty using void type.

You need to change the request type to include params if you want to pass it to the request as you done in the second approach.

Reading from your code the request type should be:

type Request = {
  type: string,
}

Closing because such questions belong to Stack Overflow.