Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'redux-observable' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
test('find', function (t) {
const cid = createCid()
const action$ = Action$.of(cats.actions.find(cid))
const feathers = {
find: () => Rx.Observable.of(values(catsData))
}
const expected = [
actionCreators.start(cid, { service, method: 'find', args: { params: {} } }),
actionCreators.set(cid, 0, catsData[0]),
actionCreators.set(cid, 1, catsData[1]),
actionCreators.set(cid, 2, catsData[2]),
actionCreators.complete(cid)
]
cats.epic(action$, undefined, { feathers })
.toArray() // .reduce(flip(append), [])
.subscribe((actions) => {
t.deepEqual(actions, expected)
t.end()
})
it('should accept factories that get invoked with props', () => {
let reducedActions = [];
let reducer = (state, action) => {
reducedActions.push(action);
return state;
};
let store = createStore(reducer, applyMiddleware(reduxObservable()));
@dispatchOnMount(
(props) => ({ type: 'PLAIN_ACTION', value: props.value }),
(props) => () => Observable.of({ type: 'SOURCE2', value: props.value }))
class TestComponent extends Component {
}
let comp = new TestComponent({ value: 'Bilbo Bagginses' });
// fake connection?
comp.context = { store };
comp.componentDidMount();
expect(reducedActions).to.deep.equal([
{ type: '@@redux/INIT' },
{ type: 'PLAIN_ACTION', value: 'Bilbo Bagginses' },
{ type: 'SOURCE2', value: 'Bilbo Bagginses' }
// Should not be processed
{
header: { msg_type: "ignored" },
content: { data: { "text/html": "<marquee>wee</marquee>" } }
},
{
header: { msg_type: "update_display_data" },
content: {
data: { "text/plain": "i am text" },
transient: { display_id: "here" }
}
}
];
const channels = from(messages);
const action$ = ActionsObservable.of({
type: actions.LAUNCH_KERNEL_SUCCESSFUL,
payload: {
kernel: {
channels,
cwd: "/home/tester",
type: "websocket"
},
kernelRef: "fakeKernelRef",
contentRef: "fakeContentRef",
selectNextKernel: false
}
});
const epic = updateDisplayEpic(action$);
const responseActions = [];
if (done) {
actual.should.deep.equal(expectation);
done();
}
});
if (!done) {
// Handle any necessary data manipulation * this could be extended to take an array
if (replace) {
replaceValues(actual, expectation);
}
actual.should.deep.equal(expectation);
}
});
const action$ = new ActionsObservable(
testScheduler.createHotObservable(...action)
);
const responseSubs = '^!';
const response$ = testScheduler.createColdObservable(...response);
call = sinon.stub().returns(response$);
const test$ = epic(action$, store, call);
testScheduler.expectObservable(test$).toBe(...expected);
testScheduler.flush();
if (callArgs !== undefined) {
call.called.should.eq(true);
call.calledOnce.should.eq(true);
call.calledWithExactly(...callArgs).should.eq(true);
}
if (done) {
actual.should.deep.equal(expectation);
done();
}
});
if (!done) {
// Handle any necessary data manipulation * this could be extended to take an array
if (replace) {
replaceValues(actual, expectation);
}
actual.should.deep.equal(expectation);
}
});
var action$ = new _reduxObservable.ActionsObservable(testScheduler.createHotObservable.apply(testScheduler, _toConsumableArray(action)));
var responseSubs = '^!';
var response$ = testScheduler.createColdObservable.apply(testScheduler, _toConsumableArray(response));
call = _sinon2.default.stub().returns(response$);
var test$ = epic(action$, store, call);
(_testScheduler$expect = testScheduler.expectObservable(test$)).toBe.apply(_testScheduler$expect, _toConsumableArray(expected));
testScheduler.flush();
if (callArgs !== undefined) {
var _call;
call.called.should.eq(true);
call.calledOnce.should.eq(true);
(_call = call).calledWithExactly.apply(_call, _toConsumableArray(callArgs)).should.eq(true);
}
const ctreateStoreWithReduxObservableMiddleware = (services) => {
const reducer = (state = [], action) => state
.concat(action)
.filter(({ type }) => ['@@redux/INIT', FETCH_DATA, FETCH_CLEAR_CACHE].indexOf(type) === -1);
// create Processor
const processor = combineDelegators(
createFetchProcess(services)
);
const middleware = reduxObservable(processor);
const store = createStore(reducer, applyMiddleware(middleware));
return store;
};
const fetchEpic = ( action$, state$ ) => action$.pipe(
ofType(FETCH_START),
mergeMap(action =>{
let { value: { actiondetailPage: { actiondetail: { params } }}} = state$;
console.log(params);
let temp = "?action_digest=" + params.id;
// return apiMongodb(`get_action_details${paramsToQuery(params)}`).pipe(
return apiMongodb(`get_action_details${temp}`).pipe(
map(res => fetchFulfilled(res.response)),
catchError(error => of(fetchRejected(error.response, { status: error.status })))
)
})
);
}
// support for redux dev tools
const compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || reduxCompose
const store = createStore(
combineReducers({
form,
resource,
...reducers,
}),
initialState,
compose(
applyMiddleware(...[
createEpicMiddleware(combineEpics(...epics, resourceEpic), { dependencies: { API } }),
cacheMiddleware,
process.env.SENTRY_DSN && createSentryMiddleware(Sentry, {
stateTransformer: (state) => { return omit(state, 'session') },
}),
].filter(Boolean))
)
)
// FIXME API should not need store
configureAPI(store)
const history = createBrowserHistory()
export {
store,
history,
}
it('should return the correct action and payload', done => {
// arrange
const action$ = ActionsObservable.from(
BOOTSTRAP_COMPLETE_ACTIONS.map(type => ({ type }))
);
// act
bootstrapEndEpic(action$, mockStore(), null).subscribe(action => {
// assert
expect(action.type).toBe(BOOTSTRAP_END);
expect(action.payload).toBeUndefined();
done();
});
});
});
export const refreshAuthStart = (action$: AnyAction, state$: any) => action$.pipe(
ofType(authActions.REFRESH_AUTH_START),
withLatestFrom(state$),
// currently the TTL of AuthToken is 120 sec, so refresh every 110 sec
map(() => authService.getAuthTokenExpiration()),
switchMap((authToken: ITokenExpiration) => timer(authToken.nextRefresh * 1000, authToken.refreshInterval * 1000)
.pipe(
takeWhile(() => state$.value.auth.isAuthenticated),
switchMap(() => userService.credentialsExist()
.pipe(
switchMap(() => authService.refreshAuth()
.pipe(
switchMap((token) => of(authActions.refreshAuthSuccess(token))),
catchError((error) => [authActions.refreshAuthFail(error.message)])
)
)
)
)