useNavigation() is a React hook. Hooks only work inside React components that are rendered inside a navigator. But App.tsx is not a screen, it’s your root component, so there’s no navigation context there. That’s why React Navigation throws.
I think you should use navigationRef for this case. (standard practice)
Here is code attached:
create RootNavigation.ts :
import { createNavigationContainerRef } from '@react-navigation/native';
export const navigationRef = createNavigationContainerRef();
export function navigate(name: string, params?: object) {
if (navigationRef.isReady()) {
navigationRef.navigate(name as never, params as never);
}
}
Attach ref to your NavigationContainer :
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<NavigationContainer ref={navigationRef}>
{/* your Stack.Navigator / Tab.Navigator goes here */}
</NavigationContainer>
);
}
Use navigate in Centrifugo callback:
import { Centrifuge } from 'centrifuge';
import Toast from 'react-native-toast-message';
import { navigate } from './RootNavigation';
useEffect(() => {
const centrifuge = new Centrifuge("wss://centrifugo.xxxxx.xxxxxx/connection/websocket", {
token: "xxxxxxxxxxxxxxxxxxxx"
});
centrifuge.on('connected', ctx => {
console.log(`centrifuge connected over ${ctx.transport}`);
}).connect();
const sub = centrifuge.newSubscription("xxxxx", {
token: 'xxxxxxxxxxxxxxxxxxxx'
});
sub.on('publication', ctx => {
Toast.show({
type: "success",
text1: ctx.data['message']
});
navigate('DetailHistory', {
id: ctx.data['transaction_id']
});
}).subscribe();
return () => {
centrifuge.disconnect();
console.log('Centrifuge client disconnected on cleanup.');
};
}, []);
Hope this fixes your problem.
THANK YOU !