solid-docs icon indicating copy to clipboard operation
solid-docs copied to clipboard

Why does the createStore function alter original store object?

Open fenprace opened this issue 3 years ago • 1 comments

When creating a store with an object, the original object passed in is altered:

In the code below, I understand the flow that the createStore takes an object and turns it into a reactive store, and the values within the object are going to be changed by setState. But I think most developers do not expect that the createStore function will have side-effect to its parameter, and it can be confusing to change a parameter implicitly.

If this behaviour is intentional, I think it could be better documented and emphasized, tell developers an object should be deep-cloned before it becomes a store, if they want their object untouched.

const DefaultState = { counter: 0 };

const [state, setState] = createStore(DefaultState);

const Root: Component = () => {
  const handleInc = () => {
    setState('counter', (c) => c + 1);
  };

  const handleReset = () => {
    // Does not not reset
    // because the original DefaultState has been changed
    setState(DefaultState);
    console.log(DefaultState);

    // This works, because it creates a new object
    // setState({ counter: 0 })
  };

  return (
    <main>
      Count: {state.counter}
      <button onClick={handleInc}>Inc</button>
      <button onClick={handleReset}>Reset</button>
    </main>
  );
};

Live Demo at here: https://stackblitz.com/edit/vitejs-vite-zjwiso?file=src/main.tsx

fenprace avatar Apr 04 '22 05:04 fenprace

I personally don't find it very surprising to begin with and I think that the docs are relatively clear

The create function takes an initial state, wraps it in a store, and returns a readonly proxy object and a setter function.

But I agree that maybe it would be better to be more explicit and add a warning like you said that if you don't want your object to be mutated you should deep clone it.

orenelbaum avatar Apr 04 '22 06:04 orenelbaum

Deploy Preview for solid-docs ready!

Name Link
Latest commit a4318a9360dd22f6416887828550c9c1c7590c35
Latest deploy log https://app.netlify.com/sites/solid-docs/deploys/62e87750670a1d000956bfe4
Deploy Preview https://deploy-preview-122--solid-docs.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

netlify[bot] avatar Aug 02 '22 01:08 netlify[bot]

Thank you so much!

You're great 😉

boehs avatar Aug 02 '22 01:08 boehs