Skip to content

Instantly share code, notes, and snippets.

@oakley808
Created September 14, 2016 20:17
Show Gist options
  • Save oakley808/e181dd05c9982fba96424a647d235334 to your computer and use it in GitHub Desktop.
Save oakley808/e181dd05c9982fba96424a647d235334 to your computer and use it in GitHub Desktop.
Generator functions post data and to watch for location change
function* main() {
// create variable for watcher
const watcherInstance = yield fork(watcher);
// if location changes, continuation
yield take(LOCATION_CHANGE);
yield cancel(watcherInstance); // cancel task instance
}
function* watcher() {
try {
while (true) {
const action = yield take(POST_CONFIGURATION);
yield call(sendConfiguration, action);
}
} finally {
if (yield cancelled()) {
console.log('watcher cancelled');
}
}
}
function sendConfiguration(action) {
const { payload: { values, resolve, reject } } = action;
const url = `${apiHost}/some/api/endpoint`;
const data = values.toJS();
fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => {
if (response.ok) {
resolve(response);
} else { // Network 404 error
reject(new SubmissionError({ _error: 'Network error.' }));
}
})
.catch(error => {
reject(new SubmissionError({ _error: `Server error: ${error}` }));
});
}
export default [
main,
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment