Object.assign
against stores - proxy(obj)
vs obj
. Why do both work?
#1002
-
When resetting store with another object I use By work I mean that Valtio continues to track values, meaning it is working Object.assign(scheduleStore, defaultStore) // ✔ (i used to think it would not work tbh)
Object.assign(scheduleStore, proxy(defaultStore)) // ✔ App that was testedScheduleView -> DayView -> LessonView (has 2 inputs to update store, namely lesson's name and place) import { proxy } from 'valtio'
import { useProxy } from 'valtio/utils'
import './style.css'
type Day = {
lessons: Lesson[]
}
type Lesson = {
name: string
place?: string | null
}
type Schedule = {
name: string
days: Day[]
}
const scheduleStore = proxy<Schedule>({
name: 'ЛИТО',
days: [
{
lessons: [
{
name: 'Эстетика',
place: '103 ИМО',
},
],
},
],
})
export default function App() {
const $schedule = useProxy(scheduleStore)
function reassignSchedule() {
Object.assign(scheduleStore, {
name: 'ЛОМО',
days: [
{
lessons: [
{
name: 'Физ-ра',
place: 'Спортивный зал ПГУ',
},
],
},
],
} satisfies Schedule)
}
return (
<div>
<pre>{JSON.stringify($schedule, null, 2)}</pre>
<button onClick={reassignSchedule}>Reassign</button>
<ScheduleView schedule={$schedule} />
</div>
)
}
function ScheduleView({ schedule }: { schedule: Schedule }) {
return (
<div>
<ul>
{schedule.days.map((_, i) => (
<DayView schedule={schedule} dayIndex={i} key={i} />
))}
</ul>
</div>
)
}
function DayView({ schedule, dayIndex }: { schedule: Schedule; dayIndex: number }) {
return (
<ul>
{schedule.days[dayIndex].lessons.map((_, i) => (
<LessonView key={i} lessonIndex={i} schedule={schedule} dayIndex={dayIndex} />
))}
</ul>
)
}
function LessonView({ schedule, dayIndex, lessonIndex }: { schedule: Schedule; dayIndex: number; lessonIndex: number }) {
return (
<div>
<input
type='text'
defaultValue={schedule.days[dayIndex].lessons[lessonIndex].name}
onChange={(e) => {
schedule.days[dayIndex].lessons[lessonIndex].name = e.target.value
}}
/>
<input
type='text'
defaultValue={schedule.days[dayIndex].lessons[lessonIndex].place ?? ''}
onChange={(e) => {
schedule.days[dayIndex].lessons[lessonIndex].place = e.target.value
}}
/>
</div>
)
} Attaching a video Code_f7BPg9cfiu.mp4 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Bonus, using |
Beta Was this translation helpful? Give feedback.
-
Yes, when assigning, we make proxies. The simpler one is this: const obj = {}
const state = proxy({});
state.obj = obj; // this and
state.obj = proxy(obj); // this are the same thing. We don't recommend this pattern, though, since Valtio v2. (Check the migration note.) |
Beta Was this translation helpful? Give feedback.
Yes, when assigning, we make proxies. The simpler one is this:
We don't recommend this pattern, though, since Valtio v2. (Check the migration note.)