Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
vuex push into nested array

I'm trying to add an object to a nested array but am not sure how to achieve this using store / vuex. I have no problems updating the main comments array using a mutation but am stuck on how to specify which main comment to push the new reply object to. The pushReply mutations adds the reply to EVERY instance of a comment.

VUEX:

export const state = () => ({
  comments: [
    {
      id: 1,
      likes: 0,
      postDate: '12/22/2021 1:25pm',
      name: 'amyrobson',
      img: '/img/avatars/image-amyrobson.png',
      post: `Impressive! Though it seems the drag feature could be improved.
              But overall it looks incredible. You've nailed the design and the
              responsiveness at various breakpoints works really well.`,

      replies: [
        {
          id: 1,
          likes: 0,
          postDate: '12/22/2021 1:25pm',
          name: 'Reply One',
          img: '/img/avatars/image-avatar.png',
          post: `Lorem ipsum
                dolor sit amet consectetur adipisicing elit. Veniam a aut quis
                recusandae magnam tenetur porro autem minima aspernatur
                voluptatum`,
        },
    
      ],
    },
  ],
})

export const mutations = {
  pushComment(state, comment) {
    state.comments.push(comment)
  },


    pushReply(state, comment) {
      state.comments.forEach((item) => {
      item.replies.push(comment)
    })
  },
    }

component:

methods: {
    addComment() {
      this.isSending = true

      // postDate
      const newDate = new Date()
      const currentDate = newDate.toLocaleDateString('en-US')
      const currentTime = newDate.toLocaleTimeString([], {
        timeStyle: 'short',
      })
      const createdAt = `${currentDate} ${currentTime}`

      setTimeout(() => {
        this.$store.commit('comments/pushComment', {
          id: this.$store.state.comments.comments.length + 1,
          likes: 0,
          postDate: createdAt,
          name: 'ramsesmiron',
          img: this.image,
          post: this.formValues.comment,
          replies: [],
        })
        this.$formulate.reset('formAddComment')
        this.isSending = false
      }, 1000)
    },
  },
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should specify on which comment you want to add this reply object. Either by passing the comment id to pushReply or by adding this id to the reply object (like parentId). Then, in the pushReply function, find the comment by this id and add this reply to it.

You have several ways as this one:

const state = {
  comments: [
    {
      id: 1,
      replies: [],
      parentId: null,
    },
    {
      id: 2,
      replies: [],
      parentId: null,
    },
    {
      id: 3,
      replies: [],
      parentId: null,
    },
  ],
};

const reply = {
  id: 1,
  replies: [],
  parentId: 2,
};

function pushReply(state, comment) {
  if (null === comment.parentId) return; // handle this case, maybe throw an error
  state.comments.find((item, i) => {
    if (item.id === comment.parentId) {
      state.comments[i].replies.push(comment);
    }
  });
}

pushReply(state, reply);
console.log(state);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda