Search code examples
javascriptvue.jsvuex

"Write operation failed: computed property "posts" is readonly"


I try remove post from PostList, but getting an error

<PostList
    :posts="sortedAndSearchedPosts"
    @remove="removePost"
    v-if="!isPostsLoading"
  />

remove post function

 removePost(post) {
      this.posts = this.posts.filter((p) => p.id !== post.id);
    },

posts initialized here

 computed: {
    ...mapState({
      posts: (state) => state.post.posts,
    }),
    ...mapGetters({
      sortedPosts: "post/sortedPosts",
      sortedAndSearchedPosts: "post/sortedAndSearchedPosts",
    }),
  },

Solution

  • Not clear where this.posts are actually initially set up. If I guess your architecture right, I see 2 options for you:

    • either directly remove the post in your store so that sortedAndSearchedPosts reflects the change directly
    • if you don't want to update the global state, build a local copy when you initialise posts:
    data () {
       return {
          posts: [...this.sortedAndSearchedPosts],
          ...
       }
    },
    

    and update your code to use the local list of posts:

    <PostList
        :posts="posts"
        ...
      />
    

    Hope this helps!