I have a basic tab navigation HOME-UPLOAD-PROFILE. 'HOME' screen has values which fetch with an api from a different web site. After user log in navigation system direct user to this home page and "fetch" working well. But when i upload something using 'UPLOAD' screen and then return 'HOME' screen datas not updating. Whereas 'componentDidMount' should works everytime and bring datas every clicking 'HOME' screen I could not find any solution or answere
export default class Home extends Component {
state = {
data: []
};
async componentDidMount() {
//Burada kullanıcı yoksa ülkeleri getireceğiz
const rest = await fetch(
'https://www.birdpx.com/mobile/fotografgetir/' + this.state.page,
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(datam)
}
);
const gelenVeri = await rest.text();
let convertedVeri = JSON.parse(gelenVeri);
this.setState({
data: convertedVeri
});
}
}
You can check by logging if componentDidMount is triggered.
componentDidMount won't be triggered when you navigate between tabs in tabNavigator, except for the first time when tabNavigator is mounted.
You can choose one of the following 2 ways to implement what you need.
1. Use global redux state instead of component state. (Recommended)
You can implement redux to your project (if you aren't using). Use redux state in Home component instead of current component state.
On Upload screen, once uploading is done you can change the redux store by dispatching an action. This will instantly reflect on your Home component.
2. Fetch data on component focus event
If you want to catch the focus event for a specific tab component, you can use didFocus event listener of navigation lifecycle.
const didFocusSubscription = this.props.navigation.addListener(
'didFocus',
payload => {
console.debug('didFocus', payload);
}
);
// Remove the listener when you are done
didFocusSubscription.remove();
If you are using react-navigation, components do not unmount when you navigate from one screen to the next on a stack navigator.
You can listen to navigation lifecycle events in a component (https://reactnavigation.org/docs/4.x/navigation-prop/#addlistener---subscribe-to-updates-to-navigation-lifecycle)
or if you are using withNavigationFocus HOC for passing navigation prop to a component you can use the isFocused prop to know about the recent focus on you component.
Related
https://wix.github.io/react-native-navigation/docs/basic-navigation#navigating-in-a-stack
indicates that pushing a new screen to the stack requires the current screen's componentId. My use case is to allow navigating based on certain events emitted by a native module. As such, componentId won't be available to me, since the event listener would reside outside any React component screen. Is there any way to navigate to a screen from outside in RNN? Or even get the current componentId.
I ended up adding a command event listener to store the current componentId in closure.
let currentComponentId;
Navigation.events().registerCommandListener((name, params) => {
if (name === 'push') {
currentComponentId = params.componentId;
}
});
Navigation.events().registerAppLaunchedListener(() => {
Navigation.setRoot(rootRouteConfig);
EventEmitter.addListener('navigate', (name) => {
Navigation.push(currentComponentId, {
component: {
name,
},
});
});
});
I setup notification system with firebase and react native. It's working fine, but when i receive notification in any state of app(killed, fore or background) and do click notification push me to home screen. I want to go on notification screen when someone click on notification.
How it will possible?
First, you have to add a Firebase Notification listener at the top-level component. I'll suggest placing it in App.js.
Foreground Listener
Background Listener
After that, You have to navigate to a particular screen with the help of a navigation prop. if you place the listener at App.js then you will not have access to the navigation prop since App.js will return the navigation container.
For that, you have to create one helper function like this navigation without prop
e.g.
export const App = () => {
messaging().setBackgroundMessageHandler(async remoteMessage => {
navigate('Notification'); //navigate to notification screen
});
const unsubscribe = messaging().onMessage(async remoteMessage => {
//generate local notification using your preferred library
//handle navigation
})
return <RootNavigator />;
};
I am creating an app in React Native (create react native) and I am attempting to fetch data from an API every time a user transitions to a screen.
For navigation, I am using the React Navigation library with a combination of Drawer and Stack Navigators.
Typically, I have seen fetch handled via the ComponentDidMount() lifecycle. However, when navigating to a screen in a stack navigator, the ComponentDidMount() lifecycle doesn't appear to trigger and the fetch doesn't run.
Ex. user is on post index, then navigates to add post screen, submits and is redirected to view screen (for that post), then clicks back to return to index. Returning to index does not trigger ComponentDidMount() and fetch isn't run again, so results are not updated.
Additionally, sometimes I need to access navigation params to alter a fetch request when navigation between screens.
I originally was attempting to determine screen transition (when navigation params were passed) via componentWillReceiveProps() method, however, this seemed a bit unreliable.
I did more reading and it sounds like I should be subscribing to listeners (via react navigation). I am having a hard time finding recent examples.
Current process (example)
On the desired screen I would subscribe to listener(s) in the componentDidMount() method:
async componentDidMount() {
this.subs = [this.props.navigation.addListener('willFocus', payload => this.setup(payload))];
}
Based of an example, it sounds like its good practice to remove all subs when unmounting the screen, so I also add:
componentWillUnmount() {
this.subs.forEach((sub) => {
sub.remove();
});
}
then I add a setup() callback method that calls whatever fetch methods I require:
setup = (payload) => {
this.getExampleDataFromApi();
};
Additionally, sometimes I need to access Navigation params that will be used in API queries.
I am setting these params via methods in other screens like so:
goToProfile = (id) => {
this.props.navigation.navigate('Profile', {
exampleParam: 'some value',
});
};
It seems like I cannot access the navigation prop via the provided getParam() method when within callback method from a navigation listener.
For example, this returns undefined.
setup = (payload) => {
console.log(navigation.getParam('exampleParam', []));
};
Instead I am having to do
componentDidFocus = (payload) => {
console.log(payload.action.params.exampleParam);
};
Question
I wanted to ask if my approach for handling fetch when navigating seems appropriate, and if not, what is a better way to tackle handling API requests when navigating between screens?
Thanks, I really appreciate the help!
I am using react-navigation in my project and I need to detect if the user is on the Dashboard/Graph/Posts page.
For example, if I am on Posts page, I need a param to write a conditional.
e.g. Make a request if I am only at Posts page
Is it possible to check on which screen the user is?
You can get it through navigation object, try it
this.props.navigation.state.routeName
You can try the following,
on componentDidMount
componentDidMount() {
this.subs = this.props.navigation.addListener("didFocus", payload => {
console.log("PAY_LOAD...", payload);
// Check the payload and your logic(you can get the current screen name like => payload.state.routeName)
});
}
on componentWillUnmount
componentWillUnmount() {
this.subs.remove();
}
Note: Don't forgot to remove listener on 'componentWillUnmount()'
I'm trying to do auth sign-out with react-native and am experiencing an issue where I want to reset the state of the redux store but, because I am using react-navigation, I have a bunch of redux-connected screens that are still mounted that re-render when the state tree is reset to it's initialState causing a bunch of exception errors. I tried to unmount them on sign-out with a react-navigation reset which redirects the user to the signup/login screen but I have no way of knowing when these screens are actually unmounted in order to call the RESET_STATE action. Initially I was dispatching the action via saga.
sagas/logout.js
import { LOGOUT, RESET_STATE } from 'Actions/user';
// clear localstorage once user logs out.
const clearData = function* clearData(action) {
AsyncStorage.removeItem('user');
yield put(
NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'SignedOut' })
],
})
);
// causes re-renders, screens still mounted
yield put({type: RESET_STATE});
}
export default function* logoutSaga () {
yield all([
yield takeEvery(LOGOUT, clearData),
]);
}
I also tried to reset once user reaches the SignedOut screen in it's componentDidMount cycle but unfortunately the screens unmount at some point well after componentDidMount is triggered:
screens/SignedOut.js
import { resetState } from 'Actions/user';
import ActionButton from 'Components/FormElements/ActionButton';
class SignedOut extends Component {
// screens are still mounted, causing screens from
// previous screens to throw exception errors
componentDidMount() {
this.props.dispatch(resetState());
}
componentWillUnmount() {
// never called
}
handleSignup = () => {
this.props.navigation.navigate('Signup');
}
handleLogin = () => {
this.props.navigation.navigate('Login');
}
render() {
return(
<Container>
<ActionButton
text="Sign Up"
handleButtonPress={this.handleSignup}
/>
<ActionButton
text="Log In"
handleButtonPress={this.handleLogin}
/>
</Container>
);
}
}
export default connect()(SignedOut);
My question is, can anyone think of a way to reset state of redux store after all of my screens have finally unmounted by the react-navigation reset action?
The issue is you're using navigate to navigate to the login/signup screen which leaves all your other components mounted, you should probably use back or reset to unmount all the components and show the login screen.
After thinking about this for a long time, I figured out that maybe I should have been focusing on the errors thrown instead of why I was getting errors. (I did learn a lot though).
Although figuring out how to listen for when all the screens are completely unmounted after calling a reset would have been super helpful, it would have just been a shortcut to bypass the real issue, the initialState for certain branches of my redux state was wrong. After correcting this no more errors, no matter when react-navigation decides to unmount the old screens.
As i have no idea how ur state looks like, which is always the issue here, why not try to use componentWillUnmount on all those components, to set a state variable and check that when you want to reset navigation?