Behavior of Valtio when adding new objects into state #305
-
Consider a state like so: class AppState
{
public employees: Employee[] = [];
}
export const appState = proxy(new AppState()); I can add a new employee to the state and if I retrieve and mutate the employee, I get the expected behavior: import { appState } from 'store/AppState'
appState.employees.push(new Employee());
const employee = appState.employees[appState.employees.length - 1];
employee.compensation = '$100,000';
// UI reacts to this change On the other hand, if I create the employee, add it to the array and adjust the compensation, it does not work as I initially expected: import { appState } from 'store/AppState'
const employee = new Employee();
appState.employees.push(employee);
employee.compensation = '$100,000'; // Some subsequent update to the object property
// UI doesn't react to this change I think I understand the reason why because the instance retrieved from So my followup question is what is whether there is a better pattern in this case? Could I make the employee object reactive before pushing it into the state? Perhaps the better pattern here is to treat the const employee = appState.CreateEmployee();
employee.compensation = '$100,000'; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Thanks for trying valtio!
Exactly.
I would do this: import { appState } from 'store/AppState'
const employee = proxy(new Employee());
appState.employees.push(employee);
employee.compensation = '$100,000'; So, valtio primitives are for function style.
I think you can do it on your end, creating such a factory function. |
Beta Was this translation helpful? Give feedback.
Thanks for trying valtio!
Exactly.
I would do this:
So, valtio primitives are for function style.
I think you can do it on your end, creating such a factory function.