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

State Between Components in the Specified Configuration #73

Closed
AFK-Python opened this issue Sep 14, 2023 · 1 comment
Closed

State Between Components in the Specified Configuration #73

AFK-Python opened this issue Sep 14, 2023 · 1 comment

Comments

@AFK-Python
Copy link

Is there a way to share state between components in the config? Other than abusing dom tricks? Or is the state of each component isolated?

From my understanding, it would likely be the latter, and that makes more sense for what Puck is trying to achieve, but for my use case I would be hoping that there might be a way to share state. Global states would work as well.

@chrisvxd
Copy link
Member

Hey @AFK-Python!

You should be able to share state without DOM tricks by using React context, defining a provider using the root configuration. Something like:

import { createContext, useContext, useState } from "react";

const context = createContext({
  counter: 0,
  setCounter: (value: number) => {},
});

const { Provider } = context;

const config = {
  root: {
    render: ({ children }) => {
      const [counter, setCounter] = useState(0);

      return <Provider value={{ counter, setCounter }}>{children}</Provider>;
    },
  },
  components: {
    MyComponent: {
      render: () => {
        const { counter, setCounter } = useContext(context);

        return (
          <>
            <div>Clicked {counter} times</div>
            <button onClick={() => setCounter(counter + 1)}>Click me</button>
          </>
        );
      },
    },
  },
};

Let me know if that works! Going to close the issue.

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