index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import Vuex from 'vuex'
  2. import md5 from 'md5'
  3. const createStore = () => {
  4. return new Vuex.Store({
  5. state: {
  6. headlines: [],
  7. loading: false,
  8. category: '',
  9. token: null,
  10. country: 'us',
  11. user: null
  12. },
  13. mutations: {
  14. setHeadLines (state, headlines) {
  15. state.headlines = headlines
  16. },
  17. setLoading (state, loading) {
  18. state.loading = loading
  19. },
  20. setCategory (state, category) {
  21. state.category = category
  22. },
  23. setCountry (state, country) {
  24. state.country = country
  25. },
  26. setToken (state, token) {
  27. state.token = token
  28. },
  29. setUser (state, user) {
  30. state.user = user
  31. }
  32. },
  33. actions: {
  34. async loadHeadLines ({ commit }, apiUrl) {
  35. commit('setLoading', true)
  36. const { articles } = await this.$axios.$get(apiUrl)
  37. commit('setLoading', false)
  38. commit('setHeadLines', articles)
  39. },
  40. async authenticateUser ({ commit }, userPayload) {
  41. try {
  42. commit('setLoading', true)
  43. const autuUserData = await this.$axios.$post(
  44. '/register/',
  45. userPayload
  46. )
  47. const avatar = `http://gravatar.com/avatar/${md5(autuUserData.email)}?d=identicon`
  48. const user = { email: autuUserData.email, avatar }
  49. commit('setUser', user)
  50. commit('setToken', autuUserData.idToken)
  51. commit('setLoading', false)
  52. } catch (error) {
  53. console.log(error)
  54. }
  55. }
  56. },
  57. getters: {
  58. headlines: state => state.headlines,
  59. loading: state => state.loading,
  60. category: state => state.category,
  61. country: state => state.country,
  62. isAuthenticated: state => !!state.token,
  63. user: state => state.user
  64. }
  65. })
  66. }
  67. export default createStore