skip to Main Content

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 };

2

Answers


  1. Chosen as BEST ANSWER

    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;
    

  2. if you want <Chat/> and <Annotation/> to share a context, you must put a single provider higher up the tree that they are both child components of. example:

    const ParentComponent = () => {
        return (
            <AppContext.Provider>
                <Chat/>
                <Annotation/>
            </AppContext.Provider>
        )
    }
    

    unlike Redux, which is global, createContext/useContext pull from the next higher-up provider.
    from the docs:

    useContext returns the context value for the calling component. It is determined as the value passed to the closest SomeContext.Provider above the calling component in the tree. If there is no such provider, then the returned value will be the defaultValue you have passed to createContext for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.

    https://react.dev/reference/react/useContext

    so in your situation, you have two separate providers handling their own state, not sharing a single provider.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search