How to change navigationState in material tabs react hooks?

253 Views Asked by At

Basically, I want to re-render my tab navigator item on state change but it will not re-render, even if the state changes, unless navigationState changes. So, my question is: How can I force my tab navigator to change navigationState when my state updated?

Here is my code:

const [isShow, setIsShow] = useState(false);
useEffect(() => {
    setTimeout(() => {
      AsyncStorage.getItem('user_type').then(response => {
        if (response == 'admin') {
          setIsShow(true)
        }
      })
    }, 5000);
  }, [isShow]);

return (
    <Tab.Navigator>
      <Tab.Screen> ... </Tab.Screen>
  
  {isShow ? (
   <Tab.Screen> ... </Tab.Screen>
  ) : null}
</Tab.Navigator>
1

There are 1 best solutions below

3
Cristian Riță On

Try doing it like this

const [isShow, setIsShow] = useState(false);
useEffect(() => {
    setTimeout(() => {
      AsyncStorage.getItem('user_type').then(response => {
        if (response == 'admin') {
          setIsShow(true)
        }
      })
    }, 5000);
  }, []);

return (
    <Tab.Navigator>
      <Tab.Screen> ... </Tab.Screen>
  
  {isShow ? (
   <Tab.Screen> ... </Tab.Screen>
  ) : null}
</Tab.Navigator>

The second parameter of the useEffect hook is a dependency array. The effect is executed only if a dependency changes. In your case, isShow is initialized with false and stays like this. Specifying an empty array [], means your effect will execute once, when the component is mounted.