Hora
Hora

Reputation: 194

Call API automatically when opening DrawerNavigation

I am consuming the data from this API, using useEffect. What works only the first time you open the component.

What I want, is that every time the data changes in the API. Change the component information.

When I use useIsFocused or useFocusEffect, I get the error: couldn't find a navigation object. is your component inside a screen in a navigator.

 const [infoUser, setInfoUser] = useState([]);

  const getNameUser = async () => {
    try {
      const accessToken = await AsyncStorage.getItem('@access_token');
      /* console.log('Token', accessToken); */

      axios
        .get(
          'https://exampleapi/api/cliente',
          {
            headers: { Authorization: `Bearer ${accessToken}` },
          },
        )
        .then(function (response) {
          // handle success
          console.log('DADOS USER:', response.data.data.nomeCompleto);
          const userData = response.data.data;

          setInfoUser([userData]);
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        });
    } catch (e) {
      // error reading value
      console.log('Erro de token', e);
    }
  };

useEffect(() => {
    getNameUser();
  }, []);

Upvotes: 0

Views: 691

Answers (1)

Hassan Kandil
Hassan Kandil

Reputation: 1866

Using useEffect hook by passing empty array like this:

useEffect(() => {
    getNameUser();
  }, []);

Giving it an empty array acts like componentDidMount as in, it only runs once.

Giving it no second argument acts as both componentDidMount and componentDidUpdate, as in it runs first on mount and then on every re-render for example:

useEffect(() => {
    getNameUser();
  });

Upvotes: 1

Related Questions