Passing nested property on state object to be updated down component tree? #637
Unanswered
jameschetwood
asked this question in
Q&A
Replies: 2 comments 3 replies
-
Interestingly if I pass an object then it does work:
https://codesandbox.io/s/bold-https-bz383d?file=/src/App.js:24-492 |
Beta Was this translation helpful? Give feedback.
1 reply
-
@dai-shi I have a similar use case, where child components want to subscribe to and mutate nested state: class Team {
leader?: User = undefined
users: User[] = []
// ...
}
class User {
name = ''
wage = 0
// ...
}
const state = proxy<Team[]>([ /* ... */ ])
const App = () => {
const teams = useSnapshot(state)
return (
<div>
{teams.map((team) => <TeamView team={team} />)}
</div>
)
}
const TeamView = React.memo((props: { team: Team }) => {
const { team } = props
return (
<div>
{team.users.map((user) => <UserView user={user} />)}
</div>
)
})
const UserView = React.memo((props: { user: User }) => {
// Subscribes to a User instance and also updates it
const { user } = props
return (
<div>
Name:
<input
type="text"
value={user.name}
onChange={(e) => { user.name = e.target.value }}
// ^^^^^^^^^
// Oops, user is a snapshot so I can't update it
/>
</div>
)
}) If I pass a snapshot made with |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Updating the state from a component works when you import and mutate the state object directly:
However id like to pass down the property on the state object to be updated. This isn't working, is something similar possible?:
https://codesandbox.io/s/quizzical-rubin-nkyrno?file=/src/App.js
Beta Was this translation helpful? Give feedback.
All reactions