RxJs and redux-observable. Append value when ajax succeed or failed
I have the following epic:
export const changeTeamSubscriptionPlan = (braintreePlanId: string) => ({
type: CHANGE_TEAM_SUBSCRIPTION_PLAN,
braintreePlanId,
});
export const changeTeamSubscriptionPlanEpic = (action$: any, store: Store<ReduxState, *>) =>
action$.ofType(CHANGE_TEAM_SUBSCRIPTION_PLAN)
.mergeMap(({ braintreePlanId }) => {
const state = store.getState();
const { subscription_id } = state.payment.subscription;
let request;
if (subscription_id) {
request = ajax(api.changeTeamSubscriptionPlan(subscription_id, braintreePlanId));
} else {
const [method] = state.payment.paymentMethods;
request = ajax(api.createSubscription(braintreePlanId, method.token));
}
// I would like to emit another value ({ type: FETCH_TEAM }) no matter what happens
//(basically I try to invalidate the team data even if the request fails)
return request
.map(response => ({
type: CHANGE_TEAM_SUBSCRIPTION_PLAN + SUCCESS,
payload: {
data: response.response,
status: response.status,
},
}))
.catch(error => Observable.of({
type: CHANGE_TEAM_SUBSCRIPTION_PLAN + FAILURE,
response: {
data: error.xhr.response,
status: error.xhr.status,
},
}));
});
What I want to do is no matter if ajax
call ends with catch or calls map I want to append another value.
I run out of ideas, so I'm hoping for help.
1 answer
-
answered 2018-01-11 20:42
Tomasz Mularczyk
After switching to original operators it turned out that I can do this:
return request .map(response => ({ type: CHANGE_TEAM_SUBSCRIPTION_PLAN + SUCCESS, payload: { data: response.response, status: response.status, }, })) .catch(error => Observable.of({ type: CHANGE_TEAM_SUBSCRIPTION_PLAN + FAILURE, error: mapToError(error), })) .concat(Observable.of({ type: 'CHUJ_TYPE' }));
and
concat
will append value even when the catch block fires.I was originally using custom operator which I though will work just like
catch
does but will reduce boilerplate in my app:Observable.prototype.mapFailure = function catchAndMapError(ACTION_TYPE, optionalPayload = {}) { return Observable.create(subscriber => this.subscribe( value => subscriber.next(value), (error) => { try { const action = { type: ACTION_TYPE + FAILURE, error: { ...mapToError(error), ...optionalPayload, }, }; subscriber.next(action); } catch (e) { // catch mappings error subscriber.error(e); } }, () => subscriber.complete(), ), ); };
It seems like it doesn't work the same as
catch
.....
See also questions close to this topic
-
React Router with Redux Loop - Reducers may not dispatch actions
I'm trying to navigate to the previous screen after a redux action. I'm using
react-router
withreact-router-redux
andredux-loop
.Here's the scenario:
- On the home screen that there's a list of users
/home
. - Tap on a user to go to their profile
/home/profile/1234
. - Edit users name and tap save
this.props.dispatch(UserState.updateUser(id, user, history)
. - Once the user is updated successfully, go back to the home screen
/home
.
Here's some code:
View:
saveProfile = () => { const user = { name: this.state.name } this.props.dispatch(UserState.updateUser(this.state.id, user, this.props.history)) }
Action:
export function updateUser(id, user, history) { return { type: UPDATE_USER, payload: { id, user, history } } }
Reducer:
case UPDATE_USER: return loop( state.updateIn(['users', action.payload.id], user => user.merge(fromJS(action.payload.user))), Effects.constant(action.payload.history.goBack()) )
This results in an error
Reducers may not dispatch actions
.On a different project, I've used
redux-saga
and was able to successfully pass the history object to the saga and push/goBack. There seems to be something going on with trying to pass the history object and calling it withinredux-loop
I'm working on a POC for an updated navigation system for an existing production app, so working with
redux-loop
is required.Any tips/help would be greatly appreciated. Please let me know if I'm missing any code that would be helpful.
- On the home screen that there's a list of users
-
Chart style function not working
working with react + redux and I’m using react charts to render data in a bar graph. With chartJs, putting the 'stack' all as ‘1’ stack the bars on each other but you split it up like a normal bar chart so I am trying to make a button that makes it alternate between these two.
This is the set up
const template = { labels: [], datasets: [ { label: 'Consumer', backgroundColor: 'black', stack: '1', data: [] }, { label: 'Producer', backgroundColor: 'grey', stack: '1', data: [] }, { label: 'In Transit', backgroundColor: 'silver', stack: '1', data: [] } ] };
And this is the function Im trying to get to work and the render:
function stackBars(e) { templateCopy.datasets[1].stack = 2 templateCopy.datasets[2].stack = 3 console.log('The link was clicked.'); console.log(templateCopy.datasets[0].stack); } return ( <div> <Bar data={data} /> <button onClick={stackBars}>Stacked</button> <button>Split</button> </div> ) }
I haven’t added the second one yet as I am still trying to get this to work.The button and the function work as I can see the console log but it’s the switch that isn’t taking effect.
Also, I pass this component into a different one to be rendered. Am I doing it wrong or is that just not possible to do?
-
Delete request redirecting too fast using React-Router
so I'm using React-Router to make a simple blog page. The DELETE request works fine, however it redirects to the index page before the post has been deleted, causing an error if you click on said post (id is not defined). I have set up a call back on the action creator to ensure the request finishes before redirecting, as well as on the deletePost function that is being called. However it is still redirecting before the request finishes deleting, thanks for taking a look!
posts_show.js with onDeleteClick function
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost } from '../actions'; import { deletePost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } onDeleteClick() { const { id } = this.props.match.params; this.props.deletePost(id, () => { this.props.history.push('/'); }); } render() { const { post } = this.props; if(!post) { return <div> Loading.. </div> } return <div className="container"> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> <Link to="/" className="btn btn-secondary"> Back </Link> <Link to="/" className="btn btn-danger btn-sm ml-2" onClick={this.onDeleteClick.bind(this)} >Delete</Link> </div>; } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
actions/index.js with deletePost request
import axios from 'axios'; export const FETCH_POSTS = 'fetch_posts'; export const CREATE_POST = 'create_post'; export const FETCH_POST = 'fetch_post'; export const DELETE_POST = 'delete_post'; const ROOT_URL = 'http://reduxblog.herokuapp.com/api'; const API_KEY = '?key=dmitriiiii88'; export function fetchPosts() { const request = axios.get(`${ROOT_URL}/posts${API_KEY}`) return { type: FETCH_POSTS, payload: request } } export function createPost(values, callback) { const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, values) .then(() => callback()); return { type: CREATE_POST, payload: request } } export function fetchPost(id) { const request = axios.get(`${ROOT_URL}/posts/${id}${API_KEY}`) return { type: FETCH_POST, payload: request } } export function deletePost(id, callback) { const request = axios.delete(`${ROOT_URL}/posts/${id}${API_KEY}`) .then(() => callback()); return { type: DELETE_POST, payload: id } }
-
ActivatedRoute.paramMap.switchMap Error
In the ngOnInit method of my component the following line is producing an error.
this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type')));
This is the error produced:
BrandComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: this.route.paramMap.switchMap is not a function at BrandComponent.ngOnInit (brand.component.ts:22) at checkAndUpdateDirectiveInline (core.js:12369) at checkAndUpdateNodeInline (core.js:13893) at checkAndUpdateNode (core.js:13836) at debugCheckAndUpdateNode (core.js:14729) at debugCheckDirectivesFn (core.js:14670) at Object.eval [as updateDirectives] (BrandComponent_Host.ngfactory.js? [sm]:1) at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655) at checkAndUpdateView (core.js:13802) at callViewAction (core.js:14153)
This is the component:
export class BrandComponent implements OnInit { private products:Product[]; private products$: Observable<Product[]>; constructor(private route:ActivatedRoute, private brandService: BrandService) { } ngOnInit() { this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); } private getProductsForType(type) { console.log('BrandComponent.getProductsForType() called') return this.brandService.getProductsForType(type); } }
At the moment, BrandService.getProductsForType() method is returning an empty array:
@Injectable() export class BrandService { private productsUrl:string = '/api/products/all'; private products:Product[]; constructor(private http:HttpClient, private dataService:DataService) { } public getProductsForType(type:string) : Observable<Product[]> { console.log('BrandService.getProductsForType() called') // return this.dataService.getProductsForType(type); return of([]) } }
-
ngrx, rxjs, and angular 5
I have attempted to figure out a simple timer observable for a couple of weeks now with no luck. I originally posted this last week: ngrx and angular 5 on stackoverflow and didn't get anywhere. I tried implementing what was suggested and got a little further with my original solution. At this point I have a timer that is emitting and outputting the countdown but only when a play or pause button is clicked. I am trying to get the countdown to continue emitting values to the display component while the play button is pushed. I have console logged the timer and it emits the values while play is pushed fine but the display component does not. I can't figure this out. I am new to Angular 5 and to ngrx/rxjs.
I have the project code available in a working form on Stackblitz here. I have the project code available in a working form on Stackblitz here.
You can login with user: test password: test
The timer code is in core/services/pomo-timer.ts
The container component is books/containers/selected-book-page.ts
The display component is books/components/book-detail.ts
At the moment it should display 6 seconds and once the play button is pushed it should emit and display each second countdown until the pause button is pushed at which time it should pause until play is clicked again. As I mentioned, when I console.log the values the work just fine. It is only when displayed in the component that they don't.
From UI: log in with test/test. Search for a book. Add To Collection. Click Through to Detail Page. There is a play and pause button. Displayed on the page are three variations of the timer I have tried from solutions found on StackOverflow. The timer starts with 6 seconds and counts down to zero. play is clicked the timer begins. pause is clicked the timer stops until play clicks again. on the display page the emitted values are not counting down. with console open, it does countdown emitted values.
The timer is handled by core/services/pomo-timer.ts
startTimer() { const resumeButton = document.getElementById('resume'); const pauseButton = document.getElementById('pause'); const resetButton = document.getElementById('reset'); const interval$: any = interval(1000).pipe(mapTo(-1)); const pause$ = fromEvent(pauseButton, 'click').pipe(mapTo(false)); const resume$ = fromEvent(resumeButton, 'click').pipe(mapTo(true)); const timer$ = merge(pause$, resume$).pipe( startWith(interval$), switchMap(val => (val ? interval$ : empty())), scan((acc, curr) => (curr ? curr + acc : acc), this.countdownSeconds$), takeWhile(v => v >= 0), ) .subscribe( val => { this.timeRemaining = val; console.log(this.timeRemaining); }, val => { this.checkTime.emit(val); }, () => { this.resetTimer(); }); }
The display is handled by app/books/components/book-detail.ts
export class BookDetailComponent { @Input() simpleObservable: number; @Input() seconds: string; @Input() timeRemaining: number; @Input() timerSubscription: Subscription; @Input() book: Book; @Input() inCollection: boolean; @Output() add = new EventEmitter<Book>(); @Output() remove = new EventEmitter<Book>(); @Output() resumeClicked = new EventEmitter(); @Output() checkTime: EventEmitter<number> = new EventEmitter(); get id() { return this.book.id; } get title() { return this.book.volumeInfo.title; } get subtitle() { return this.book.volumeInfo.subtitle; } get description() { return this.book.volumeInfo.description; } get thumbnail() { return ( this.book.volumeInfo.imageLinks && this.book.volumeInfo.imageLinks.smallThumbnail ); } get time() { return this.timeRemaining; } resumeCommand(action: any) { this.resumeClicked.emit(action); } }
The communication with the timer service is handled by: app/books/containers/selected-book-page.ts
@Component({ selector: 'bc-selected-book-page', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <bc-book-detail [book]="book$ | async" [inCollection]="isSelectedBookInCollection$ | async" [timeRemaining]="this.pomoTimerService.timeRemaining" [simpleObservable]="this.simpleObservable | async" [seconds]="this.pomoTimerService.timeRemaining" (checkTime)="checkCurrentTime($event)" (add)="addToCollection($event)" (remove)="removeFromCollection($event)" (resumeClicked)="resumeClicked($event)" (resumeClicked)="resumeClicked($event)" (reset)="resumeClicked($event)"> </bc-book-detail> `, }) export class SelectedBookPageComponent implements OnInit { book$: Observable<Book>; isSelectedBookInCollection$: Observable<boolean>; timeRemaining: any; private timerSubscription: Subscription; timerSource = new Subject<any>(); simpleObservable; countDown: any; counter: number; seconds: string; private subscription: Subscription; checkTime; constructor(public pomoTimerService: PomoTimerService, private store: Store<fromBooks.State>) { this.book$ = store.pipe(select(fromBooks.getSelectedBook)); this.isSelectedBookInCollection$ = store.pipe( select(fromBooks.isSelectedBookInCollection) ); } ngOnInit(): void { this.pomoTimerService.pomoCount$ = 0; this.pomoTimerService.pomosCompleted$ = 0; this.pomoTimerService.pomoTitle$ = 'Time to Work'; this.pomoTimerService.initTimer(); } addToCollection(book: Book) { this.store.dispatch(new collection.AddBook(book)); } removeFromCollection(book: Book) { this.store.dispatch(new collection.RemoveBook(book)); } resumeClicked(event) { console.log(event); console.log(event.target); console.log(event.srcElement); console.log(event.type); console.log(event.currentTarget.attributes.name.nodeValue); console.log(event.currentTarget.attributes.id.nodeValue); if (event.currentTarget.attributes.id.nodeValue === 'resume' && !this.pomoTimerService.timerStarted) { this.pomoTimerService.timerStarted = true; this.pomoTimerService.startTimer(); } } checkCurrentTime(event) { this.counter = event; } }
The pomo-timer.ts is outputting the timer via
this.remainingTime
Any assistance you might be able to provide would be greatly appreciated. I have tried all examples that are even remotely related that I have found here on Stackoverflow as well. Thank you very much. -
Passing a value between services in Angular5 using RxJs
I am trying to pass an access_token , which is declared in userService service, and its value is set in register.component.ts. Then I need to access the value of the access_token in another service (httpService). I decided to use BehavioralSubject for that matter but somehow i cannot retrieve updated value of the token in httpService. The code excerpt below.
User.service.ts -> here i declare the access_token
access_token = new BehaviorSubject<string>('');
Register.component.ts -> here i successfully assign the value to access_token
onRegister(form){ this.httpService.registerByEmail(this.email, this.password ) .subscribe( response => { this.popupService.popupScreen.next('messenger'); this.httpService.loginByEmail(this.email, this.password) .subscribe(response1 => { this.userService.access_token.next(response1['access_token']); console.log('access_token Component', this.userService.access_token); --> here it console.logs the correct token }, error => { console.log('error', error); } ) }, error => { if (error.error.status === false) { this.emailError = error.error.errors.email; this.passwordError = error.error.errors.password; }; } ) }
Http.service.ts -> here is where i need to retrieve the updated value of the token
access_token; getSubject(){ this.userService.access_token.subscribe( token => { this.access_token = token }); return this.access_token; } setLogin(): Observable<any[]> { this.getSubject(); const url = 'http://url'; const httpHeaders = new HttpHeaders() .set('Authorization', 'Bearer ' + this.access_token); return this.httpClient.post<any[]>(url, { headers: httpHeaders }); }
-
How get the Vue instance from vuetify with vue-axios
I create a project with Vuetify and vue-axios, and create a simple login component, but I have problem to get the Vue instance
this is my login component:
<template> <v-app id="inspire"> <v-content> <v-container fluid fill-height> <v-layout align-center justify-center> <v-flex xs12 sm8 md4> <v-card class="elevation-12"> <v-toolbar dark color="primary"> ... </v-toolbar> <v-card-text> ... </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="primary" @click='logar()'>Entrar</v-btn> </v-card-actions> </v-card> </v-flex> </v-layout> </v-container> </v-content> </v-app> </template> <script> export default { name: 'Login', data: () => ({ drawer: null, checkbox: false, username: 'cartorio@teste.com.br', password: '1234', }), props: { source: String, }, methods: { logar() { var myVue = this.$vuetify; this.axios.post('http://localhost:8585/login', { email: this.username, senha: this.password, }, { withCredentials: false, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }, ).then((response) => { //HERE I NEED TO USE myVue window.AUT = response.headers.authorization; }).catch((error) => { console.log(error); }); }, }, }; </script>
so, inside axios promisse, then I need to use my var myVue, so why always get undefined?
tks
-
How to correctly use axios params with arrays
How to add indexes to array in query string?
I tried send data like this:
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })
And I got this url:
http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3
So, I should to get this url:
http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3
What I should add in my params options to get this url?
-
Parent state not updating after function fired
I have declared the state in the parent to determine whether a use is logged in or not as per below
class App extends Component { constructor(props) { super(props) this.state = { isLoggedIn: false } } render() { <div> { (document.cookie && this.state.isLoggedIn) ? ( <LoggedInHeader/> ) : <HomeHeader/> }
In order for a user to be logged in I make an axios request to an api that in turn gives me a token that I store in the browser cookie, the code below is from my log in modal component, I explicitly update the state after the axios request is made to true, the state updates in the console as I would expect but when I check whether the boolean is true or false it is in the original state. I am aware that "setState() does not immediately mutate this.state" but still can't seem to get the state to change. Login form component below which is a child of the app parent.
loginSubmitHandler = (event) => { event.preventDefault() const user = "email=" + this.state.email + '&password=' + this.state.password const instance = axios.create({ baseURL: 'http://weburl', timeout: 1000, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }); instance.post('/login', user) .then(res => { let d = new Date d.setDate(d.getDate() + 30) let expires = "expires=" + d document.cookie = "sessionname" + "=" + res.data.success.token + expires + ";path=/" console.log('changing state') this.setState({ isLoggedIn: true }, () => {console.log('New state', this.state)}) }) .catch(err => { console.log(err, "There was an error") })}
-
Observable epics not running service call
I try to follow the example in the documentation to test epic:
Epic
import { ofType } from 'redux-observable'; import { combineEpics } from 'redux-observable'; import 'rxjs/add/operator/takeUntil'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { switchMap } from 'rxjs/add/operator/switchMap'; import { from } from 'rxjs/observable/from'; import { of } from 'rxjs/observable/of'; import { fromPromise } from 'rxjs/observable/fromPromise'; import { getTopStories } from '../../../utils/service-helper'; import { type, actions } from './action'; export const getHackernewsStoryEpic = (action$, store) => action$.ofType(type.GET_HACKERNEWS_STORIES_REQUEST) .switchMap( action => { return from(getTopStories()) .takeUntil(action$.ofType(type.GET_HACKERNEWS_STORIES_REQUEST_CANCEL)) .map(result => actions.getHackernewsStoriesRequestSuccess(result)) .catch((error) => actions.getHackernewsStoriesRequestFailure(error)) } ); export default combineEpics( getHackernewsStoryEpic );
Get getTopStories is service call which talks to hackernews API:
export const getTopStories = async () => await getRequest('/topstories.json');
My test looks like this:
describe('Hackernews stories epic', () => { describe('getHackernewsStoryEpic', () => { let store; beforeEach(() => { store = mockStore(); }); afterEach(() => { nock.cleanAll(); epicMiddleware.replaceEpic(storiesEpic); }); it('should return success on request success', async () => { store.dispatch({ type: type.GET_HACKERNEWS_STORIES_REQUEST }); expect(store.getActions()).toEqual([ { type: type.GET_HACKERNEWS_STORIES_REQUEST }, { type: type.GET_HACKERNEWS_STORIES_SUCCESS } ]); }); }); });
Looking at the test it fails as one action is trigger and getTopStories() is never trigger (nock is not complaining that there is no mock) and not getting next action. I think I missing something as from should run async call?
-
Filter Observable of Observables
The streams are http requests and the main observable is created by me.
-------stream1-----------------stream2-------------------------stream3----------> -------1----2----3--4--5---5--7-> --2--4-5----7--8-----> ------4---6---3---6->
Is there a way to give the streams ids as metadata or something and filter them and then subscribe only to the innerObservable stream that is left:
Rx.Observable // stream1: id = 12 // stream2: id = 13 // stream3: id = 14 .filter(x => x.id === 12) .switchMap(x => x) .subscribe( x => x)
-
combineLatest doesn't emit latest value
I'm having difficulty wrapping my head around why
combineLatest
isn't returning the latest value. This example is a bit contrived but at least it illustrates my problem. Notice the value ofcolor
from thecombineLatest
observable returns a previous value, when thesubject.value
is correct. It's like thecolor$
observable hasn't emitted.import { map, distinctUntilChanged, combineLatest } from 'rxjs/operators' import { Observable } from 'rxjs/observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; const main$ = new BehaviorSubject({color: 'red'}); const color$ = main$.pipe( map(state => state.color), ) main$.pipe( combineLatest(color$) ) .subscribe(([state, color]) => { console.log(state, color, main$.value.color); }) main$.next({ color: 'yellow' });
Actual Output
{color: "red"} "red" "red" {color: "yellow"} "red" "yellow" {color: "yellow"} "yellow" "yellow"
Expected Output
{color: "red"} "red" "red" {color: "yellow"} "yellow" "yellow" // Notice middle value is yellow {color: "yellow"} "yellow" "yellow"
https://stackblitz.com/edit/combine-latest-issue
If someone could help explain whats going, and provide a workaround or proper way to think about this in
rxjs
I would appreciate it. -
update data for a reactJs app when consuming data from socketIo
I am new to ReactJs and trying to find the best approach to update the UI based on new data from the socket( using socket IO). I am using redux-observable epic to output the action which provides the new data.
import socketIo from 'socket.io-client'; import Rx from 'rxjs/Rx'; import { INTIATE_DATA_STREAM, DATA_STREAM_EVENTS, STOP_STREAM, } from 'actions/test'; const socket = socketIo(window.location.origin, { reconnect: false }); const dataStream$ = Rx.Observable.fromEvent(socket, 'somedata'); export const dependencyMapStreamEpic = action$ => action$.ofType(INTIATE_DATA_STREAM) .switchMap(() => depDataStream$ .map(payload => ({ type: DATA_STREAM_EVENTS, payload, })) .takeUntil( action$.ofType(STOP_STREAM), ), );
and in the component, I am updating inside the
componentWillUpdate(nextProps, nextState)
lifecycle method but keep getting the error
invariant.js:42 Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
So should I evaluate the difference and then only execute the update action?
edit 1: updating the componentWillUpdate method:
componentWillUpdate(nextProps) { if (nextProps.someData.nodes[1].nodes.length > 0) { this.updateData(nextProps.someData); } }
-
Redux Observables / RxJS: If statements with multiple conditions?
I want to do something like:
- If node.foo.length < 5 -> nodeActions.addFoo()
- After node.foo.length >= 5, if node.bar.length < 5 -> nodeActions.addBar()
Is there a way to do this without having two separate epics?
const addFoo = (action$, store) => { return action$ .ofType(nodeActions.NODE_DETERMINE_REQUEST) .filter(() => { const { node } = store.getState(); return node.foo.length <= 5; }) .map(nodeActions.addFoo); }; const addBar = (action$, store) => { return action$ .ofType(nodeActions.NODE_DETERMINE_REQUEST) .filter(() => { const { node } = store.getState(); return node.bar.length <= 5 && node.foo.length >= 5; }) .map(nodeActions.addBar); };
-
Passing store to switchMap function in observable epic
I need to pass store value to switchMap function on epic but seems like only action is passed and store is 0.
export const addVideoEpic = (action$, store) => action$.ofType(videoTypes.ADD_VIDEO_REQUEST) .filter(() => of(store.getState())) .switchMap((action, store) => { const data = { url: store.url }; console.log(store) // 0 return from(addVideo(data)) });
How to pass store value down to switchMap