Reputation: 394
Is there any way to navigate with useNavigation hook to a class component ?
This is my class:
export default class AzureLogin extends React.Component
So i need to navigate to the AzureLogin
from Screen1
.
what is the way to do it ?
import { useNavigation } from '@react-navigation/native';
const Screen1 = (props) => {
const [data, setData] = useState('');
const [isLoaded, setIsLoaded] = useState(false);
const dispatch = useDispatch();
const userState = useSelector((state) => state.userReducer);
const [isSync, setIsSync] = useState(false);
const syncData = useGetUserDevicesData(isSync);
useEffect(() => {
if (syncData.isLoaded === true) {
setIsSync(false);
setData(syncData.data);
}
}, [syncData.isLoaded]);
useEffect(() => {
const getItem = async () => {
const azureToken = await AsyncStorage.getItem('AZURE-TOKEN');
const userName = await AsyncStorage.getItem('AZURE-USERNAME');
const googlToken = await AsyncStorage.getItem('GOOGLE-TOKEN');
const deviceId = await AsyncStorage.getItem('DEVICE-ID');
const platformId = await AsyncStorage.getItem('PLATFORM-TYPE');
getSaveUserTokenData({
userName,
googlToken,
platformId,
deviceId,
azureToken,
});
};
getItem();
}, []);
const getSaveUserTokenData = async (data) => {
const navigation = useNavigation();
const url =
'https://' +
'userName=' +
data.userName +
'&userToken=' +
data.googlToken +
'&PlatformType=' +
data.platformId +
'&DeviceID=' +
data.deviceId;
await fetch(url, {
method: 'GET',
headers: {
Authorization: data.azureToken,
},
})
.then((response) => response.json())
.then((data) => {
console.log(
'THE FETCH DATA TO getSaveUserTokenData FUNCTION IS:',
data
);
})
.catch((error) => {}); //**HERE I NEED TO NAVIGATE !!**
};
Upvotes: 0
Views: 540
Reputation: 1053
Being able to navigate a screen doesn't depend on whether it is a functional or a class component. So you can navigate to AzureLogin of course.
But as #1 Rules of Hooks clearly states
Only Call Hooks at the Top Level
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
So, based on your Screen1 component,
You should move your useNavigation
hook from getSaveUserTokenData
to the top level like below:
const Screen1 = (props) => {
const [data, setData] = useState('');
const [isLoaded, setIsLoaded] = useState(false);
const dispatch = useDispatch();
const userState = useSelector((state) => state.userReducer);
const navigation = useNavigation();
...
Only then, you can call navigation.navigate('AzureLogin')
inside wherever you want.
Upvotes: 1