react-nativecreatecontext

React createContext running mutation function not working correctly


I am having a problem i can't seem to understand why is happening since i have the same example working in codesandbox, but in my app it shows a different behavior. In my app i can see the context from the consumer both the bool and the function, but when i run the function it runs the empty function "setUpdate: () => {}" instead of running the "updBool()" in UpdateDataProvider.js file. Anyone know why this behaviour happens. (component.js is not my actual file just a short example of how im using the context)

UpdateDataProvider.js

    export const UpdateDataContext = createContext({
        update: false,
        setUpdate: () => {},
    });
    
    export function UpdateDataContexProvider({ children }) {
        function updBool(bool) {
            setU({ ...u, update: bool });
        }
        const [u, setU] = useState({ update: false, setUpdate: updBool });
    
        return (
            <UpdateDataContext.Provider value={u}>
                {children}
            </UpdateDataContext.Provider>
        );
    }

useUpdateData.js

    import { useContext } from 'react';
    import { UpdateDataContext } from '../../context/updateDataContext';
    
    export function useUpdateDataContext() {
        return useContext(UpdateDataContext);
    }

component.js

    import { UpdateDataContexProvider } from '../../context/updateDataContext';
    import { useUpdateDataContext } from '../../hooks/exports';

    useEffect(() => {
      // loging the context shows me update bool and setUpdate function
      console.log(context)
      // Running the function will run the empty function in createContext
      // in UpdateDataProvider.
      context.setUpdate(true)
    }, [])
    
    export default Home = () => {
         const context = useUpdateDataContext()
        
         return (
         <UpdateDataContexProvider>
             <Other />
         </UpdateDataContexProvider>
        )
    }

Solution

  • Don't mind my question, the mistake was that i was trying to run the function in useEffect in the home component but not the childs