The server node.js updates data every 0.5 seconds. The client has to poll the server and fetch new data using RxJS. I have made the client to poll server, the requests are made but I cant read the response from the server. I think that the state is not updated due to poll_server returning timer.pipe() or the reducer is creating a wrong state. I came to this from my teacher's template, so why the dispatcher would return an Observable?
model.js
export function init_state(warnings) {
return {
warnings,
accept: ({ visit_site }) => { if (visit_site) return visit_site(warnings) }
}
}
dispatcher.js
import { from, of, timer } from 'rxjs'
import { concatMap, map } from 'rxjs/operators'
import { FRONT_PAGE } from './constants'
const poll_server = url => {
return timer(0, 3000)
.pipe(concatMap(() => from(fetch(url))
.pipe(map(response => response.json())))
)
}
export const server_dispatch = action => {
switch (action.type) {
case FRONT_PAGE: {
const res = poll_server('http://localhost:8080/warnings')
console.log(res)
return res
}
default:
return of(action)
}
}
reducer.js
export function reduce(state, action) {
switch (action.type) {
case FRONT_PAGE:
console.log(`REDUCER CALLED WITH ACTION ${FRONT_PAGE}`)
return init_state(action)
default:
return state
}
}
The problem is that you want to call poll_server which will start an observable stream on an ajax endpoint from within the reducer (which implies you would subscribe to this stream here, not the way you are currently using it), which isn't how redux is supposed to be used. Reducers are intended by its creator to be pure functions without causing side effects.
If you want to use redux with observables, it is advised to use custom middleware to handle these side effects. The most obvious middleware I suggest is https://redux-observable.js.org/, which I've tried in the past and works without trouble.
The documentation is exquisite, and you will use this without trouble if you are already familiar with RX principles.