I have a problem with derived store, which somehow returns an empty result even tho in the store is 1 record. The derived store depends on 2 writable stores: assignedAgentsIds
(array of agent ids) and agents
(map of agent entity). If I use both stores directly in a component, it works just fine, but when I use them in a derived store and try to combine them, I'm always getting empty array.
Here is my store code:
const createAssignedAgentsStore = () => {
const assignedAgentIds = writable<string[]>([])
const { subscribe, set, update } = assignedAgentIds
const setAssignedAgentIds = (agentIds: string[]) => {
set(agentIds)
}
const addAssignedAgentId = (agentId: string) => {
update((agentIds) => [...agentIds, agentId])
}
return {
subscribe,
setAssignedAgentIds,
addAssignedAgentId,
}
}
export const assignedAgentIds = createAssignedAgentsStore()
export const assignedAgents = derived([assignedAgentIds, agents], ([$assignedAgentIds, $agents]): Agent[] => {
const assignedAgentsArr: Agent[] = []
for (const agentId of $assignedAgentIds) {
const agent = $agents[agentId]
if (agent) assignedAgentsArr.push(agent)
}
return assignedAgentsArr
})
I tried to debug both $assignedAgentIds
and $agents
inside derived store, it has correct values and if there is 1 id in assignedAgentsIds
and 1 record with the same id in agents
map, still when I use $assignedAgents
store in component, I get empty array instead of an array with 1 entity.
Edit
In Svelte component, I had this code to show correct type of agents which was also using assignedAgents
store:
let headerAgents: Agent[] = []
$: {
let agentsArray = Object.values($agents)
if ($assignedAgents.length > 0) {
agentsArray = $assignedAgents
}
headerAgents = agentsArray.splice(0, 3)
}
I was passing reference to the
assignedAgents
store in component and mutating the store withsplice
function. Solution is to not mutate store by usingslice
function.This is code that works: