Created
November 21, 2018 14:34
-
-
Save KidkArolis/f8163e785e3f165b873d402d99ea186a to your computer and use it in GitHub Desktop.
Fetch and take latest
This file contains hidden or 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 axios from 'axios' | |
import fetch from './fetch' | |
export default { | |
async fetchPage ({ dispatch }, { query, headers }, ref) { | |
// every time this action is dispatched, make the request using the fetch helper | |
// which ensures we cancel previous requests and only mutate state after the latest one | |
await fetch(ref, { | |
request: cancelToken => { | |
return Promise.all( | |
[ | |
axios.get(`${apiEndpoint}/api/jobs`, { params: query, cancelToken, headers }), | |
axios.get(`${apiEndpoint}/api/categories`, { cancelToken, headers }), | |
axios.get(`${apiEndpoint}/api/locations`, { cancelToken, headers }), | |
axios.get(`${apiEndpoint}/api/types`, { cancelToken, headers }) | |
].map(p => p.then(res => res && res.data)) | |
) | |
}, | |
done: result => { | |
const [jobs, categories, locations, types] = result | |
dispatch('receiveJobs', jobs) | |
dispatch('receiveCategories', categories) | |
dispatch('receiveLocations', locations) | |
dispatch('receiveTypes', types) | |
} | |
}) | |
} | |
} |
This file contains hidden or 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 axios from 'axios' | |
export default async function fetch (ref, { request, error, done }) { | |
if (ref.source) { | |
ref.source.cancel('No longer needed') | |
delete ref.source | |
} | |
ref.source = axios.CancelToken.source() | |
const cancelToken = ref.source.token | |
let result | |
try { | |
result = await request(cancelToken) | |
} catch (err) { | |
if (axios.isCancel(err)) { | |
return | |
} else if (error) { | |
error(err) | |
} else { | |
throw err | |
} | |
} finally { | |
delete ref.source | |
} | |
if (done) { | |
done(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment