Reputation: 160
I'm trying to combine Contexts by creating 'with' functions for each Context, then use compose
function to combine them into withProviders
function, which wraps App component. But it doesn't work, state doesn't change. So, what I'm doing wrong?
Here's the example on codesandbox: https://codesandbox.io/p/sandbox/pedantic-fast-717xb9
main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.jsx
import { useAuth, withProviders } from "./withProviders";
function App() {
const [authenticated, setAuthenticated] = useAuth();
const toggle = () => setAuthenticated((b) => !b);
return (
<div className="App">
<div>{authenticated.toString()}</div>
<button onClick={toggle}>toggle</button>
</div>
);
}
export default withProviders(App);
withProviders.jsx
import { createContext, useContext, useState } from "react";
import compose from "compose-function";
const AuthContext = createContext([false, () => null]);
const withAuth = (component) => {
return function AuthProvider() {
const [authenticated, setAuthenticated] = useState(false);
return (
<AuthContext.Provider value={[authenticated, setAuthenticated]}>
{component()}
</AuthContext.Provider>
);
};
};
export const useAuth = () => useContext(AuthContext);
export const withProviders = compose(withAuth);
Upvotes: 0
Views: 63
Reputation: 781
https://codesandbox.io/p/sandbox/morning-lake-7hj8mg
Calling component as a function doesn't work properly with hooks
Use way I provided or React.createElement(component)
Upvotes: 1