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

createContext not working as expected #432

Closed
karthikcodes6 opened this issue Jun 13, 2021 · 5 comments
Closed

createContext not working as expected #432

karthikcodes6 opened this issue Jun 13, 2021 · 5 comments

Comments

@karthikcodes6
Copy link
Contributor

Hey everyone, I just tried to use the createContext API but it seems saving the state in a global and updating changes to all the contexts instead of the particular single context.

Here is the reproducible code sandbox link - here

This is the expected result here

@karthikcodes6
Copy link
Contributor Author

It seems like working now. The mistake was I initiated the store outside from the component. So, it was using the same store for all the components instead of creating a new store.

overall code

import "./styles.css";
import create from "zustand";
import createContext from "zustand/context";

const { Provider, useStore } = createContext();

// Before store = create(...)
const store = () =>
  create((set) => ({
    bears: 0,
    increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
    removeAllBears: () => set({ bears: 0 })
  }));

const Button = () => {
  return (
    <Provider initialStore={store()}>
      {/** Before - initialStore={store} */}
      <ButtonChild />
    </Provider>
  );
};

const ButtonChild = () => {
  const state = useStore();
  return (
    <div>
      {state.bears}
      <button
        onClick={() => {
          state.increasePopulation();
        }}
      >
        +
      </button>
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <Button></Button>
      <Button></Button>
    </div>
  );
}

@dai-shi
Copy link
Member

dai-shi commented Jun 13, 2021

I originally suggested to pass createStore={create} to the Provider to avoid this misusing, but then we discussed and agreed that initialStore={create()} is more flexible. Maybe a doc issue?

@karthikcodes6
Copy link
Contributor Author

Yes, the documentation is incorrect.

@dai-shi
Copy link
Member

dai-shi commented Jun 13, 2021

Mind opening a PR?

@karthikcodes6
Copy link
Contributor Author

Sure. I'm on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants