Svelte Kit Reactivity for Nested Properties Using Svelte Store

160 Views Asked by At

I'm trying to update a specific blog thumbnail path inside a block property using the handleUpdateEditableContent function. The blocks get updated, but the image element doesn't reflect the new thumbnail path. How can I fix this?

Snippet that display img

<img
    class="object-cover object-center w-full lg:h-48 md:h-36"
    src={blog.thumbnail.path}
    alt="blog"
/>

store.ts

export const blocks = writable([
    {
        id: 1,
        type: name,
        blogs: [
            {
                id: 1,
                title: 'My blog 1',
                description: 'hello',
                external_link: '/hello',
                thumbnail: {
                    name: 'Placeholder',
                    type: 'local',
                    path: 'https://dummyimage.com/300x300'
                }
            },
            {
                id: 2,
                title: 'My blog 2',
                description: 'hello',
                external_link: '/',
                thumbnail: {
                    name: 'Placeholder',
                    type: 'local',
                    path: 'https://dummyimage.com/400x400'
                }
            }
        ]
    }
])

utils.ts

export const handleUpdateEditableContent = (oldData: any, newData: any, blockId: string) => {
    let currentBlocks: any
    const unsubscribe = blocks.subscribe((value) => {
        currentBlocks = [...value]
    })
    const updatedBlocks = currentBlocks.map((block: any) => {
        if (block.id === blockId) {
            return { ...oldData, ...newData }
        }
        return block
    })
    blocks.set([...updatedBlocks])
    console.log(currentBlocks)
    unsubscribe()
}

calling the function

let blogs = block.blogs.map((item: BlogData) => {
    if (item.id === options.id) {
        return { ...item, thumbnail: {
                name:'new image',
                path:'https://dummyimage.com/800x800',
                local:'local',
            } }
    }
    return item
})

handleUpdateEditableContent(block, { blogs: [...blogs] }, block.id)
0

There are 0 best solutions below