Search code examples
reactjsreact-context

how to share context between two functional components which will render in different createNodes ? need to invoke this code in my existing js app


Accesing state in <annotation> is not same as <chat>.

can't use redux here , quiet a small app so i ignored it.
what changes can i do in context.js to achiche this is functionality

index.js

import { AppContext,AppContextProvider } from "./context";
const BookBot = (props) => {
    const botRoot = createRoot(document.getElementById((props?.toolbox)))
    const botAnnot = createRoot(document.getElementById((props?.annotbox)))
    botRoot.render(
        <AppContextProvider>
            <Chat />
        </AppContextProvider>
    );
    botAnnot.render(
        <AppContextProvider>
            <Annotaion />
        </AppContextProvider>
    )
}

contex.js

const AppContext = React.createContext([{}, () => {}]);

const AppContextProvider = (props) => {
  const [state, setState] = useState({
    chats:[],
    query:undefined,
    sendDisabled:false,
    chatId:""
  });
  return (
    <AppContext.Provider value={[state, setState]}>
      {props.children}
    </AppContext.Provider>
    );
};

export { AppContext, AppContextProvider };

Solution

  • Finally managed to fix this using zustand.

    zustand : creates a global store

    context.js

    import { create } from 'zustand'
    const useGlobalStore = create((setState) => ({
      chats:[],
      query:undefined,
      sendDisabled:false,
      chatId:"",
      setState : setState
    
    }))
    export default useGlobalStore;