[IMP] store: prevent changes to store state in useStore return value

closes #500
This commit is contained in:
Géry Debongnie
2019-11-26 22:51:35 +01:00
committed by aab-odoo
parent 8fb35ed969
commit 1f079b883e
3 changed files with 22 additions and 2 deletions
+3
View File
@@ -274,6 +274,9 @@ Note that if the selector function returns a primitive type, the result of
is important to define the `onUpdate` option to properly update the value
manually when it changes.
Also, the return value from `useStore` is not supposed to be modified. The store
state should only be updated with actions.
### `useDispatch`
The `useDispatch` hook is useful when a component needs to be able to dispatch
+1 -2
View File
@@ -134,8 +134,7 @@ export function useStore(selector, options: SelectorOptions = {}): any {
return result[k];
},
set(target, k, v) {
result[k] = v;
return true;
throw new Error("Store state should only be modified through actions");
}
});
}
+18
View File
@@ -100,6 +100,24 @@ describe("connecting a component to store", () => {
expect(error.message).toBe("No store found when connecting 'App'");
});
test("cannot modify state returned by usestore", async () => {
const state = { a: { b: 1 } };
const actions = {};
const store = new Store({ state, actions });
class App extends Component<any, any> {
static template = xml`<div/>`;
storeState = useStore(state => state.a);
}
(<any>env).store = store;
const app = new App();
expect(app.storeState.b).toBe(1);
expect(() => (app.storeState.b = 2)).toThrow(
"Store state should only be modified through actions"
);
});
test("can use useStore twice in a component", async () => {
const state = { a: 1, b: 2 };
const actions = {