DEV Community

Discussion on: Do you need Vuex?

Collapse
rleahy22 profile image
Ryan Leahy

One method I like is using reactive, and toRefs

import { reactive, toRefs, computed } from "@vue/composition-api";
import { Article } from "../models";
import api from "../api";

const state = reactive({
  articles: [] as Article[],
  totalLikes: computed(() => state.articles.reduce((p, c) => p + c.likes, 0)),
})

const loadArticles = () =>
  api.load().then(articles => {
    state.articles = articles;
  });

const like = (incoming: Article) =>
  api.like(incoming).then(res => {
    const index = state.articles.findIndex(a => a.id === res.id);
    state.articles.splice(index, 1, res);
  });

export default {
  ...toRefs(state),
  loadArticles,
  like
};