Utilizing parameters for data filtering in VueX getters

I'm really stuck on this issue. I've been trying to retrieve a blog post object using a getter based on its "slug". Despite all my attempts, every time I try to use the getter, I keep getting an error saying "state.posts.filter" is not a function. I know for sure that there are items in the state array and it is defined as an array by default. Any thoughts on why this might be happening? Assuming that FETCH_POSTS has already been dispatched and that posts contains elements.

Not sure if this matters, but I am working with Nuxt in the modular store format.

This is how my Store looks:

import {createClient} from '~/plugins/contentful.js'
const client = createClient()

const state = {
   posts: []
}

// getters
const getters = {
   allPosts: state => state.posts,
   getPostBySlug: state => slug => state.posts.filter(post => post.fields.slug === slug)
}

// actions
const actions = {
   FETCH_POSTS: (state) => {
   // INIT LOADING
   client.getEntries({
     'content_type': 'article',
     order: '-sys.createdAt'
   })
  .then(posts => {
    // SUCCESS
    state.commit('SET_POSTS', posts.items)
  })
  .catch(error => {
    // FAILURE
    console.log(error)
  })
 }
}

// mutations
const mutations = {
   SET_POSTS: (state, posts) => {
      // Assign posts to state
      posts = posts.map(function (post) { post.fields.slug = post.fields.title.replace(/\s+/g, '-').toLowerCase()
      return post
   })
   state.posts = Object.assign({}, posts)
  }
}

export default {
 state,
 getters,
 actions,
 mutations
}

And in my component, I call it like this:

export default {
    name: 'blog-post',
    computed: {
      post: function () {
        return this.$store.getters.getPostBySlug('test-slug')
      }
    }
}

Answer №1

@Bert & @Evaldo were instrumental in guiding me towards the correct answer. Initially, I made a mistake when dispatching my "SET_POST" mutation by assigning the results to an empty object instead of the required array. The accurate approach for implementation is demonstrated below.

// mutations
const mutations = {
   SET_POSTS: (state, posts) => {
      // Assign posts to state
      posts = posts.map(function (post) { post.fields.slug = post.fields.title.replace(/\s+/g, '-').toLowerCase()
         return post
      })
      state.posts = Object.assign({}, posts)
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a div beside a button using componentDidMount in a React component

Upon page load, I aim to position an info icon div next to a button node. However, the button node is not available when componentDidMount is triggered. I have attempted to use setTimeout, but its effectiveness varies depending on the amount of data in th ...

Struggling with incorporating a lightbox within an accordion feature in an .html file

I'm currently attempting to integrate this lightbox into this accordion feature. Individually, I've managed to get both elements up and running smoothly. However, when trying to combine them on the same page (regardless of nesting one inside the ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Accessing method from child component in parent component in Vue.js is a common requirement that can be easily

Is there a way to access a method in the parent component from the child component? I attempted to use mixins but found that the function was returning null instead of the expected value. However, when emitting an object, it worked fine in the parent compo ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

The querySelector function seems to be identifying the element with the ID "submit" and another input element of type "submit"

My code includes a function that toggles between two elements' style.display values, switching them from "none" to "block" and vice versa. However, I've encountered an unexpected issue where the behavior of the "send" button seems to be linked wi ...

adding numerous items to an array using JavaScript

How can I add multiple objects to an array all at once? router.post(`/products`, upload.array("photos" , 10), async (req, res) => { console.log(res); try { let product = new Product(); req.files.forEach(file => { product.p ...

Error with NEXTJS: Prop type failed - The prop `href` in `<Link>` is expecting a `string` or `object`, but received `undefined`

After importing the Link from next/link and attempting to pass the dynamic endpoint in my components, I encountered an error message. https://i.stack.imgur.com/eqUK8.png https://i.stack.imgur.com/eIC4V.png I searched for a solution and came across a sug ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

The navigation is designed to only show up as I scroll down the page, but ideally it should be visible

I am trying to make the navigation bar appear on page load instead of when I scroll down the page. Currently, I am using this jQuery code: <script type="text/javascript> $(document).scroll(function() { if ($(this).scrollTop() == 20) { ...

Tips on improving image loading speed in JavaScript code

I'm working on a simple weather map that changes the background image depending on the current weather status. However, I've noticed that there is a delay in changing the image when the weather status changes. I'm wondering if this delay is ...

Disable the sorting feature on selected columns

I have a Datatable in JS with a scroll bar that I added using scrollY. However, it is displaying unnecessary small arrows within the table which I do not want. I have tried various methods to remove them but without success. Can someone please help me wi ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

By pairing delay(0) with refCount(), we can achieve optimal efficiency

The refCount operator is discussed in this article. It explains the necessity of adding delay(0) to prevent unsubscription of observable A: import { Observable } from "rxjs/Observable"; const source = Observable.defer(() => Observable. ...

The react-router-dom seems to be malfunctioning, so let's simply render the "/"

Struggling to render multiple pages in React, I am a newbie and have been exploring various tutorials and pages. My stack includes React, Webpack, Babel, and ESLint with Airbnb configuration. When I render my React app, it appears like this. View of the ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Everything seems to be functioning properly on the local server, but once the media files or players (mp3 and mp4) are uploaded, the background fails to work entirely

function playMusic() { var songs = [ "pump.mp3", "ybwm.mp3", "bb.mp3", ]; var randomIndex = Math.floor(Math.random() * songs.length); var selectedSong = songs[randomIndex]; var audio = new Audio(selecte ...