Skip to content

using dict store

s1n7ax edited this page Jan 31, 2023 · 2 revisions

Using dict store

⚠️ Important!

  • Arrays in the store is not possible at the moment. (I'm still figuring out how to properly tackle the store problems.)

Example

local Renderer = require('react.renderers.buffer-renderer')

local create_store = require('react.stores.dict')

local store = create_store({
    name = 'Harry Potter',
    author = {
        first_name = 'Joanne',
        last_name = 'Rowling',
        nickname = 'JK Rowling',
        country = 'UK',
        age = 57,
    },
    from = '1997',
    to = '2007',
    genre = 'Fantasy'
})


local function App()
    return {
        '----------------Book----------------\n',
        ('"%s" by %s'):format(store.name, store.author.nickname)
        '\n',
        'Genre :: ', store.genre
    }
end

local buffer = vim.api.nvim_create_buf(false, true)

local win_conf = {
    width = 100,
    height = 100,
    relative = 'editor',
    row = 1,
    col = 1,
}

vim.api.nvim_open_win(buffer, true, win_conf)

Renderer:new({
    buffer = buffer
}):render(App)

vim.defer_fn(function ()
    store.name = 'The Ink Black Heart'
    store.genre = 'Mystery, Crime fiction, Thriller, Suspense, Adventure fiction'
    store.author.nickname = 'Jo Rowling'
end, 2000)

BE AWARE OF FOLLOWING RULES/BEHAVIOUR

  • Arrays in the store is not possible at the moment. (I'm still figuring out how to properly tackle the store problems.)

  • You are not allowed to create an store inside an effect or component

-- CORRECT
local store1 = create_store({})

create_effect(function()
    -- WRONG
    local store2 = create_store({})
end)
  • Dependency will only be registered when you index the store
local store = create_store({ name = 'some name' })

create_effect(function()
    -- WRONG
    -- just because you use 'store' inside an effect, it's not going to get
    -- registered as a dependency
    -- MEANING if you update 'store' values, this effect will not be re-rendered
    local variable = store

    -- CORRECT
    -- when you index the store, effect will be added as a dependent of
    -- store.name
    local variable = store.name
end)
  • You can assign store value to another variable but assigning a value to the new variable will not re-render the component
local store = create_store({
    user = {
        name = 'some name',
    }
})

create_effect(function()
    return {
        store.user.name
    }
end)

local user = store.user

-- WRONG
-- It's is quite obvious why you shouldn't do this
-- This is pointless because you are just assigning a value to variable user
-- Following will not cause a re-render
user = {
    name = 'updated name'
}

-- CORRECT
-- assigning a value by indexing store will re-render the effect/component
store.user = {
    name = 'updated name'
}
Clone this wiki locally