Skip to content

Instantly share code, notes, and snippets.

@nikmolnar
Created July 18, 2016 22:44
Show Gist options
  • Save nikmolnar/d271917c54f33b12e2a769906bf483f6 to your computer and use it in GitHub Desktop.
Save nikmolnar/d271917c54f33b12e2a769906bf483f6 to your computer and use it in GitHub Desktop.
Experimenting with redux + async ideas...
import fetch from 'isomorphic-fetch'
import { getCookies } from './utils'
import uuid from 'node-uuid'
import { store } from '.'
class Request {
constructor() {
this.promiseUUID = null
}
_handlePromise(promise) {
let promiseUUID = uuid.v4()
this.promiseUUID = promiseUUID
return promise.then(response => {
if (promiseUUID === this.promiseUUID) {
return response
}
else {
return Promise.reject()
}
})
}
get(url) {
return this._handlePromise(fetch(url, {credentials: 'same-origin'}))
}
post(url, data, options) {
let { method } = options
if (!method) {
method = 'POST'
}
if (data) {
data = JSON.stringify(data)
}
return this._handlePromise(fetch(url, {
method,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookies().csrftoken
},
body: data
}))
}
}
export default (select, fetchData) => {
let currentState
let io = new Request()
return store.subscribe(() => {
let nextState = select(store.getState())
if (JSON.stringify(nextState) !== JSON.stringify(currentState)) {
currentState = nextState
fetchData(currentState, io, store.dispatch)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment