hookstate icon indicating copy to clipboard operation
hookstate copied to clipboard

Request: throw error when trying to assign nested state to a Proxy object

Open korri123 opened this issue 1 year ago • 2 comments

I sometimes forget to destructure or deep clone a nested Hookstate object when assigning state, which often results in a proxy object placed within the state object. When this happens, the error thrown is a "call stack exceeded" RangeError within the Hookstate library later when rendered. However, this error message doesn't provide a clear indication of the mistake.

Is it possible to implement a check to detect this specific scenario and provide a more informative error message to guide users in identifying and correcting their mistake?

korri123 avatar Apr 01 '23 21:04 korri123

It is possible but it would require deep check of all fields and nested fields which hits the performance. Maybe do it in development mode only?. When this error happens it should not have call stack exceeded exception. Can you submit a reproducer for this case so I could check if this exception can be replaced by a better one?

avkonst avatar Apr 01 '23 22:04 avkonst

@avkonst Sure! Here is a reproducer, just click the button and the error will happen: https://playcode.io/1377075 Development mode only would be fine.

Code below if website doesn't work:

import React from 'react';
import {useHookstate} from '@hookstate/core'

interface NestedObject {
  nestedNumber: number;
}

interface StateObject {
  nestedObject?: NestedObject;
  nestedObject2?: NestedObject;
}

export default function App() {
  const state = useHookstate({nestedObject: {nestedNumber: 1}} as StateObject)
  return (
    <div className='App'>
      <button onClick={function() {
        const value = state.nestedObject.get()
        state.set({nestedObject: value, nestedObject2: {nestedNumber: 2}})
      }}>Click me!</button>
      <p>{(function() {
        const nested = state.nestedObject.ornull;
        if (!nested) return null;
        return nested.nestedNumber.get()
      })()}</p>
    </div>
  );
}

korri123 avatar Apr 01 '23 23:04 korri123