Search code examples
react-nativereact-context

React Native function does not fire thru useContext


I am trying to do some conditional renders so I created a boolean called signedIn and tried to change the value from a child component. I spent a lot of time and mostly value came out as read only. Then I was able to find some other example which had setter function passed thru useContext and it worked on the example shown which was a react project. My project is react native and I can not seem to fire the function. I can read the value but cannot change it. My ContextProvider code is below:

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

const AuthContext = React.createContext();
const AuthUpdateContext = React.createContext();

export function useAuthContext() {
  return useContext(AuthContext);
}

export function useAuthUpdateContext() {
  return useContext(AuthUpdateContext);
}

export function AuthContextProvider({ children }) {
  const [signedIn, setSignedIn] = useState(true);
  function toggleSignedIn() {
    setSignedIn((prevSignedIn) => !prevSignedIn);
    console.log("fired from AuthContextProvider : toggleSignedIn");
    console.log(signedIn);
  }

  return (
    <AuthContext.Provider value={signedIn}>
      <AuthUpdateContext.Provider value={toggleSignedIn}>
        {children}
      </AuthUpdateContext.Provider>
    </AuthContext.Provider>
  );
}

Actually it would be nicer to be able to set the value of signedIn prop thru sth like js setSignedIn(newVal) but I would settle to get this work as well. My provider is wrapped around the app as suggested in many places but function does not seem to fire. This is where I use my function in the signin screen

export default function SignInScreen({ navigation }) {
  const [username, setUserName] = useState("");
  const [password, setPassWord] = useState("");
  const signedIn = useAuthContext();
  const toggleSignedIn = useAuthUpdateContext();

  const SignIn = async () => {
    try {
      await login(username, password);
      toggleSignedIn;
      console.log("toggleSignedIn fired from SignInScreen");
      console.log(toggleSignedIn);

Solution

  • You are passing the toggleSignedIn function as a value in your AuthContextProvider, but you are not using it as a function in your SignInScreen. You are simply referring to it without the brackets instead.use the function:

    function toggleSignedIn(newVal) {
      setSignedIn(newVal);
    }
    
     const SignIn = async () => {
      try {
        await login(username, password);
        toggleSignedIn(false); // or true, depending on your logic
      } catch (error) {
        // Handle errors
      }
    };