Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scoped state tracking #479

Open
christianalfoni opened this issue Jan 14, 2021 · 1 comment
Open

Scoped state tracking #479

christianalfoni opened this issue Jan 14, 2021 · 1 comment

Comments

@christianalfoni
Copy link
Member

By extending the signature of useAppState we can scope the tracking of state.

const Item = ({ id }) => {
  const item = useAppState(state => state.items[id]) // Tracks ["items.$id"] and any other accessed state on item
}

This is different than doing:

const Item = ({ id }) => {
  const item = useAppState().items[id] // Tracks ["items", "items.$id"] and any other accessed state on item
}

The second example here also tracks the "items" themselves, meaning any added/removed items will cause this component to reconcile. We can currently solve this by passing the whole item down to the component, and do useAppState without using any actual state... this new solution seems more intuitive.

@sergeyzwezdin
Copy link

sergeyzwezdin commented Nov 8, 2022

@christianalfoni from example page:

// components/Todos.tsx
import * as React from 'react'
import { useAppState } from '../overmind'
import Todo from './Todo'

const Todos = ({ id }: { id: string }) => {
  const state = useAppState()

  return (
    <ul>
      {Object.keys(state.todos).map(id => <Todo key={id} id={id} />)}
    </ul<
  )
}

export default Todos

// components/Todo.tsx
import * as React from 'react'
import { useAppState } from '../overmind'

const Todo = React.memo(({ id }: { id: string }) => {
  const todo = useAppState(state => state.todos[id])

  return <li>{todo.title}</li>
})

export default Todo

Does it actually work?
const todo = useAppState(state => state.todos[id]) returns the whole state object (root state), not specific todo, but Typescript says it's specific todo, not root state.

Overmind version:

    "overmind": "^28.0.2",
    "overmind-react": "^29.0.2",

UPDATE:

Issue is actual for Next.js, while code works on server-side. On a client-side there is no issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants