I have an array in which another array of agents is stored. In this agents array only the id of each agent is located. Using the id's, I fetch the data I need for each agent and I want to replace the original agent array with the new, completed agent data. Or at least push the new data to the specific agent. Here is what I have tried so far. Is there a simple way to do it?
How to use the fetched agent in filteredEvents? As seen in my expected result
filteredEvents: [
{
agents: ['id', 'id'], // the id's are as plain text located
eventData: ''
}
]
// Expected result
filteredEvents: [
{
agents:
[
{ id: '', name: '', ...}, // the data from the fetched id
{ id: '', name: '', ...},
],
eventData: ''
}
]
otherAgentsEvents() {
// Not that relevant currently
// const events = this.events
// const user = this.getUser._id
// const filteredEvents = events.filter(event => !event.agents.includes(user));
filteredEvents.forEach(event => {
const agents = event.agents
agents.forEach(agent => {
const data = this.fetchAgentData(agent)
// replace 'event.agents[agent]' with this data
})
})
return filteredEvents
}
async fetchAgentData(agentID) {
try {
const agent = await this.$axios.$get(`/api/get-specific-agent/${agentID}`)
if (agent.success) {
return agent.data
}
} catch (err) {
console.log(err)
}
}
Html for better understanding
<div v-for="(event, key) in otherAgentsEvents" :key="key">
<div v-for="agent in event.agents" :key="agent.id">
// Currently I haven't access to first_name etc.
// only to agent where only the plain ID is stored
<p>{{ agent.first_name }}</p>
</div>
<div>
{{ event.eventData }}
</div>
</div>
Update based on tao's answer
I have tried to implement the code, but am probably doing something wrong. Here's what I did.
I use vuex
, I have never worked with pinia
. Reactive is not defined, I left it out. I don't know where to get it.
import axios from 'axios'
const store = {
agents: [],
getAgent: (id) =>
new Promise((resolve) => {
console.log(id)
const agent = store.agents.find(({ id: i }) => i === id)
if (agent) {
resolve(agent)
} else {
axios.get(`/api/get-specific-agent/${id}`).then(({ data }) => {
store.agents.push(data)
resolve(data)
})
}
}),
}
export const useAgents = () => store
otherAgentsEvents() {
// const events = this.events
// const user = this.getUser._id
// const filteredEvents = events.filter(event =>
// !event.agents.includes(user))
filteredEvents.map(async (event) => {
const agents = event.agents
event.agents = await Promise.all(
agents.map((id) => useAgents().getAgent(id))
)
return event
})
return filteredEvents
},
Here I actually achieve the wanted result for a short time, but then my app crashes with following errors.