Created
July 18, 2016 22:44
-
-
Save nikmolnar/d271917c54f33b12e2a769906bf483f6 to your computer and use it in GitHub Desktop.
Experimenting with redux + async ideas...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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