Reputation: 83
I'm using React + Redux + Rxjs + typesafe-actions
+ TS and I want to call action with params. My code for now:
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;
}),
};
And it's working - making a call to API but without params. I tried many times and still I don't know how to pass a params when dispatch is called.
Upvotes: 1
Views: 568
Reputation: 83
I found answer:
export const fetchCats = createAsyncAction(
FETCH_CATS_REQUEST,
FETCH_CATS_SUCCESS,
FETCH_CATS_ERROR
) <void, ICats, Error> ();
changed to:
type ICatsRequest = {
catType: string;
};
export const fetchCats = createAsyncAction(
FETCH_CATS_REQUEST,
FETCH_CATS_SUCCESS,
FETCH_CATS_ERROR
) <ICatsRequest, ICats, Error> ();
and then it allows me to pass specified type to dispatch:
store.dispatch(fetchCats.request({catType: 'XXX'}));
also I needed to modify this:
export const Cats = {
getDataFromAPI: (params) => $http.get('/cats', {
params: {
type: params.payload.catType
}
}).then(res => {
return res.data as any;
}),
};
and
switchMap((params) =>
fromPromise(Cats.getDataFromAPI(params)).pipe(
map(fetchCats.success),
catchError(pipe(fetchCats.failure, of))
)
)
Upvotes: 1