Search code examples
react-nativesetstate

setState is not working in react native for boolen


Here is my code, I want to change the boolen value of isCourse but is not changing. It's showing false in debugging. I also checked the if value is showing true

 const [appTheme, setAppTheme] = useState(Appearance.getColorScheme());
 const [isCourse, setIsCourse] = useState(false);

 useEffect(() => {
   const handleDynamicLinks = dynamicLinks()
     .getInitialLink()
     .then(link => {
       console.log('here is your link', link.url);
       if (link && link.url === 'https://englishmuni.page.link/course') {
         setIsCourse(true);
         // console.log('--*****--', isCourse, link.url);
       }
     });

   const unsubscribe = dynamicLinks().onLink(handleDynamicLinks);
   Appearance.addChangeListener(scheme => {
     setAppTheme(scheme.colorScheme);
   });
   return () => unsubscribe();
 }, [isCourse]);

Solution

  • You should be careful about the logic inside the useEffect to avoid infinite loops or any unintended side effects with isCourse since you're setting its value inside of it (setIsCourse).

    You can call two useEffects in which the first one without dependency array to initialize isCourse and the second useEffect to watch the changes to isCourse

    useEffect(() => {
      //You can create an async function here and put the logic inside
      const handleDynamicLinks = async () => {
        try {
          const link = await dynamicLinks().getInitialLink();
          console.log('here is your link', link.url);
          if (link && link.url === 'https://englishmuni.page.link/course') {
            setIsCourse(true);
          }
        }
        catch (error) {
          //TODO when exception occurs
        }
      };
    
      //Call the function
      handleDynamicLinks();
    
      const unsubscribe = dynamicLinks().onLink(handleDynamicLinks);
      const themeListener = Appearance.addChangeListener(scheme => {
        setAppTheme(scheme.colorScheme);
      });
    
      return () => {
        unsubscribe();
        themeListener.remove();  // Assuming the listener has a remove() method. If not, adjust accordingly.
      };
    }, []); //<-- As stated before, we setup the useEffect with no dependency when the component is mounted for the first time.
    

    Now coming on to the second useEffect where we actually observe the changes to isCourse.

    useEffect(() => {
      if (isCourse) {
        //Work with the logic here.
      }
    }, [isCourse]); //<-- And here, we observe the changes to isCourse
    

    By splitting the logic into two separate useEffect hooks, you separate the logic for setting isCourse and the logic for responding to changes in its value. This can help avoid potential pitfalls like infinite loops.