Skip to content

Instantly share code, notes, and snippets.

@KidkArolis
Created November 21, 2018 14:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KidkArolis/f8163e785e3f165b873d402d99ea186a to your computer and use it in GitHub Desktop.
Save KidkArolis/f8163e785e3f165b873d402d99ea186a to your computer and use it in GitHub Desktop.
Fetch and take latest
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)
}
})
}
}
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