Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useReactive): cannot set a object with read-only and non-configurable property #2247

Merged
merged 2 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions packages/hooks/src/useReactive/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,36 @@ describe('test useReactive feature', () => {
expect(() => result.current.v.Module).not.toThrowError();
});

it('test JSX element', () => {
const hook = renderHook(() => useReactive({ html: <div role="id">foo</div> }));
const proxy = hook.result.current;
const wrap = render(proxy.html);
const html = wrap.getByRole('id');

expect(html.textContent).toBe('foo');
act(() => {
proxy.html = <div role="id">bar</div>;
wrap.rerender(proxy.html);
});
expect(html.textContent).toBe('bar');
hook.unmount();
});

it('test read-only and non-configurable data property', () => {
const obj = {} as { user: { name: string } };
Reflect.defineProperty(obj, 'user', {
value: { name: 'foo' },
writable: false,
configurable: false,
});

const hook = renderHook(() => useReactive(obj));
const proxy = hook.result.current;

expect(() => proxy.user.name).not.toThrowError();
hook.unmount();
});

it('test input1', () => {
const wrap = render(<Demo />);

Expand Down
6 changes: 6 additions & 0 deletions packages/hooks/src/useReactive/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ function observer<T extends Record<string, any>>(initialVal: T, cb: () => void):
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver);

// https://github.com/alibaba/hooks/issues/1317
const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
if (descriptor && descriptor.configurable === false && descriptor.writable === false) {
liuyib marked this conversation as resolved.
Show resolved Hide resolved
return res;
}

// Only proxy plain object or array,
// otherwise it will cause: https://github.com/alibaba/hooks/issues/2080
return isPlainObject(res) || Array.isArray(res) ? observer(res, cb) : res;
Expand Down