pmndrs / valtio

🧙 Valtio makes proxy-state simple for React and Vanilla
https://valtio.dev
MIT License
9.16k stars 257 forks source link

How to work dynamic property keys in valtio #151

Closed MarvinAmador7 closed 3 years ago

MarvinAmador7 commented 3 years ago

Hi,

I got into a situation where I'm loading datasets into a Valtio proxy, but since I'm using dynamic property keys to store the dataset I'm getting the following error: TypeError: Cannot read property 'dataset' of undefined

I think this has something to do with how the proxies work.

This is the whole code:

import { proxy, useSnapshot } from 'valtio'

export interface DataSet {
  name: string
  dataset: Record<string, any>[]
}

type State = { sets: Record<string, DataSet>}

const state = proxy<State>({
  sets: {
    soccer: {
      dataset: [],
      name: 'Soccer Games',
    }
  },
})

export const useDataAggregator = () => {
  const snapshot = useSnapshot(state)

  const addData = ({ name, dataset }: DataSet) => {
    state.sets[name].dataset = [...dataset, ...state.sets[name].dataset]
  }

  return {
    state: snapshot,
    actions: {
      addData,
    },
  }
}

Any thoughts about what I’m missing?

dai-shi commented 3 years ago

Isn't it just how JS works?

  const addData = ({ name, dataset }: DataSet) => {
    if (!state.sets[name]) {
      state.sets[name] = {}
    }
    state.sets[name].dataset = [...dataset, ...state.sets[name].dataset]
  }
dai-shi commented 3 years ago

Closing as answered. Feel free to continue discussion.