Skip to content

To Readable

When you use readable store from svelte store, it will covert a plain value to a readable store, which what you wish for but if you try to in another store it will nest that store inside a readable store, which is not what you want in most case and this function will help you to avoid that. It will check if the value is a readable store or not and if it is it will return it as it is, if not it will convert it to a readable store.

๐ŸŽฌ Usage

<script>
    import {writable} from "svelte/store"

    import {to_readable} from "@sveu/shared"

    const num = writable(0)

    const new_num = to_readable(num)
</script>

{$new_num}

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
value The value to be converted MaybeStore<T> Yes

โ†ฉ๏ธ Returns

A readable store.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { readable } from "svelte/store"
import type { Readable } from "svelte/store"

import { is_partial_writable, is_readable_only } from "../utils"
import type { MaybeStore } from "../utils"

/**
 * A function that converts a value to a readable store, the value could be plain, writable, or even readable store
 *
 * @param value - the value to be converted
 *
 * @returns a readable store
 */
export function to_readable<T>(value: MaybeStore<T>): Readable<T> {
    if (is_partial_writable(value)) {
        return {
            subscribe: value.subscribe,
        }
    }

    return is_readable_only(value) ? value : readable(value)
}

Last update: 2023-02-09