How to structure vuex store for list of objects and mapping to them individually based on ID

Viewed 723

My photo app has a list of photoshoot sessions, where each session contains metadata such as date, time, and many images.

I wrote a Vuex module called session that stores all the info for ONE session.

const state = {
  images: [],
  date: null,
  photographerId: null
}

However, realistically I would have multiple sessions, each with their own metadata and images. I read in many places that I should create a normalized store. So what I envision that to be like is:

const state = {
  sessions: {
    session1: {
      images: [],
      date: null,
      photographerId: null 
    },
    session2: {
      images: [],
      date: null,
      photographerId: null 
    },
    ...
  }
}

To access each session, I could have a getter like:

const getters = {
  sessionById: (state) => (sessionId) => {
    return state.sessions[sessionId];
  }
}

But here comes the problem. In my current page for showing data about a specific session, I have code like:

computed: {
  ...mapState('session', ['images', 'date', 'photographerId'])
}

If I was to move to a normalized store, how can I still achieve this? I know I can map the getter instead and declare each session's attribute individually like:

computed: {
  ...mapGetters('session', ['sessionById']),
  images() {
    return this.sessionById(sessionId).images;
  },
  date() {
    return this.sessionById(sessionId).date;
  },
  photographerId() {
    return this.sessionById(sessionId).photographerId;
  }
}

But that feels pretty hacky and worse than what I had before with mapState.

I have a gut feeling I'm using Vuex wrongly, could anyone please enlighten me?

0 Answers
Related