how to use redux with routerWillLeave - javascript

So I have a setRouteleaveHook with function:
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
console.log("prompt: ", this.props.prompt);
if (this.props.prompt) {
return "Are you sure you wish to navigate? Unsaved data will be lost. Try to use the 'next' button instead if moving to the next part.";
} else {
return true;
}
}
this.props.prompt is a variable in the store. It seems that when I update it in it's parent, the prompt doesn't get altered until the next time I visit it.
Is there a better way to trigger these prompts? (Given that it is the parent component that is doing the router.push)

import {withRouter} from 'react-router';
export default withRouter(connect(YourSelectors,YourActions)(YourPage))

Related

want the app to save state separately according to each user in react native

I have a app that conducts a test and when the currently logged in user passes the test, the app shows a modal telling him that he has passed the test. I want the app to save this state for this specific user that is currently logged in and even if he closes the app, the passing screen still remains there but now if a completely new user logs in, the app should start over from the beginning, it should show the test screen 1st and then if the user passes the test, the app saves the state for him accordingly.
Long story short, I want my app to save the state for each user separately according to their case (that rather they have passed the test or not). I want a clear and simple solution to this.
Here's the code snippet for my test.js:
import React ,{useState, useEffect} from "react";
import {View, Alert, Image, StyleSheet, Text, Modal, TouchableOpacity, TouchableHighlight} from 'react-native';
import Voice from 'react-native-voice';
import auth from '#react-native-firebase/auth';
export default alpht =({navigation}) => {
function Check() {
if (results.includes(words[index])){
Alert.alert('Correct!','You are learning so well!');
if(index==7) {
if(count<=5)
{
//displaying the modal for passing screen
setshowpass(true);
}
else{
console.log(count)
Alert.alert('fail','fail');
}
}
if (index==7){
setndis(true);
setdis(true);
setidis(true);
}
else{
setndis(false);
setdis(true);
setidis(true);
}
}
else{
Alert.alert('Ops!','Looks like you went wrong somewhere. Try again!');
setcount(count+1);
setdis(true);
setndis(true);
if(count==5){
Alert.alert('Restest', 'Looks like you had way too many mistakes!')
setind(0);
setcount(0);
setdis(true);
}
}
}
const words=['ceket', 'çilek', 'elma', 'fare', 'öğretmen', 'otobüs', 'şemsiye', 'uçak'];
const [show, setshow]=useState('');
const [showpass, setshowpass]=useState(false);
useEffect(() => {
setshow(true);
}, []);
return (
..other code here
)
}
There are multiple ways you can solve the problem. you can use AsyncStorage or build more sophisticated logic using react-redux and redux-persist.
Bottom line, you just need to cache the user details/data and you can do it following my above suggestion. (My answer doesn't need code snippet)
Thanks.

Detect Back Button in Navigation Guards of Vue-Router

How the route is changed, matters for my case.
So, I want to catch when the route is changed by a back button of browser or gsm.
This is what I have:
router.beforeEach((to, from, next) => {
if ( /* IsItABackButton && */ from.meta.someLogica) {
next(false)
return ''
}
next()
})
Is there some built-in solutions that I can use instead of IsItABackButton comment? Vue-router itself hasn't I guess but any workaround could also work here. Or would there be another way preferred to recognize it?
This is the only way that I've found:
We can listen for popstate, save it in a variable, and then check that variable
// This listener will execute before router.beforeEach only if registered
// before vue-router is registered with Vue.use(VueRouter)
window.popStateDetected = false
window.addEventListener('popstate', () => {
window.popStateDetected = true
})
router.beforeEach((to, from, next) => {
const IsItABackButton = window.popStateDetected
window.popStateDetected = false
if (IsItABackButton && from.meta.someLogica) {
next(false)
return ''
}
next()
})
Slight improvement to #yair-levy answer.
Wrapping push to own navigate method is not convenient because you usually want to call push() from various places. Instead, router original methods can be patched in one place without changes in remaining code.
Following code is my Nuxt plugin to prevent navigation triggered by back/forward buttons (used in Electron app to avoid back caused by mouse additional "back" button, which makes mess in Electron app)
Same principle can be used for vanilla Vue and to track common back button together with your custom handling.
export default ({ app }, inject) => {
// this is Nuxt stuff, in vanilla Vue use just your router intances
const { router } = app
let programmatic = false
;(['push', 'replace', 'go', 'back', 'forward']).forEach(methodName => {
const method = router[methodName]
router[methodName] = (...args) => {
programmatic = true
method.apply(router, args)
}
})
router.beforeEach((to, from, next) => {
// name is null for initial load or page reload
if (from.name === null || programmatic) {
// triggered bu router.push/go/... call
// route as usual
next()
} else {
// triggered by user back/forward
// do not route
next(false)
}
programmatic = false // clear flag
})
}
As stated by #Yuci, all the router hook callbacks are performed before popstate is updated (and therefore not helpful for this use case)
What you can do:
methods: {
navigate(location) {
this.internalNavigation = true;
this.$router.push(location, function () {
this.internalNavigation = false;
}.bind(this));
}
}
Wrap 'router.push' with you own 'navigate' function
Before calling router.push, set 'internalNavigation' flag to true
Use vue router 'oncomplete' callback to set internalNavigation flag back to false
Now you can check the flag from within beforeEach callback and handle it accordingly.
router.beforeEach((to, from, next) => {
if ( this.internalNavigation ) {
//Do your stufff
}
next()
})
I found a simple way to solve this after spending a lot of time trying to refine the codes to work well in my case and without a glitch.
export const handleBackButton = () => {
router.beforeEach((to, from, next) => {
if (window.event.type == 'popstate' && from.name == 'HomePage'){
next(false);
}else{
next();
}
});
}
The window.event.type == 'popstate' checks if the back button is pressed
And from.name == 'HomePage' checks the page on which the back button is pressed or you are routing from.
HomePage as the name where you want to disable back button. You can leave this condition if you want to disable it throughout the site.
next(false) and next() to stop or allow navigation respectively.
You can place the code in a navigationGuard.js file and import it to your main.js file
I tried other methods, including calling from the components but it produces a glitch and the rerouting becomes obvious. But this leaves no glitch at all.
Hope this works for you. Cheers
I had the same problem regarding detecting Back Button navigation as opposed to other types of navigation in my Vue App.
What I ended up doing was adding a hash to my real internal App navigation to differentiate between intended App navigation and Back Button navigation.
For example, on this route /page1 I want to catch Back Button navigations to close models that are open. Imagine I really wanted to navigate to another route, I'll add a hash to that route: /page2#force
beforeRouteLeave(to, from, next) {
// if no hash then handle back button
if (!to.hash) {
handleBackButton();
next(false); // this stops the navigation
return;
}
next(); // otherwise navigate
}
This is rather simplistic, but it works. You'll want to check what the hash actually contains if you use them for more than this in your app.
performance.navigation is deprecated so whatch out! https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
When you want to register any global event listener you should be very careful with that. It will be called each time since registration moment untill you unregister that manualy. For me the case was that I have register popstate listener when component was created to listen and call some action when:
browser back button
alt + arrow back
back button in mouse
was clicked. After that I have unregister popstate listener to not call it in other components where I don't want it to be called, keep Your code and method calls clean :).
My code sample:
created() {
window.addEventListener('popstate', this.popstateEventAction );
},
methods: {
popstateEventAction() {
// ... some action triggered when the back button is clicked
this.removePopstateEventAction();
},
removePopstateEventAction() {
window.removeEventListener('popstate', this.popstateEventAction);
}
}
Best regards!
The accepted answer almost worked for me, but I found that the listener was behind by 1 click, probably due to the issue that #Yuci highlighted.
The answer from #farincz worked best for me, but since it wasn't written for vanilla Vue, I thought I'd write down what worked for me here:
// after createRouter
let programmatic = false;
(['push', 'replace', 'go', 'back', 'forward']).forEach(methodName => {
const method = router[methodName]
router[methodName] = (...args) => {
programmatic = true
method.apply(router, args)
}
})
router.beforeEach(async (to, from) => {
if(!from.name === null || !programmatic) {
// do stuff you want to do when hitting back/forward or reloading page
}
programmatic = false // clear flag
});
This is done very easily.
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
// History back position, if user click Back button
return savedPosition
} else {
// Scroll to top of page if the user didn't press the back button
return { x: 0, y: 0 }
}
}
})
Check here:
https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

How to destroy a VueJS component that is being cached by <keep-alive>

I have a Vue component that's kept alive using Vue's element for caching purposes. However, the problem I am having right now is that once I sign out of one account and create a new account on my Vue application, the component I'm "keeping alive" is being reflected for the new user (which obviously isn't relevant for the new user).
As a result, I want to destroy that component once the user signs out. What is the best way to go about this?
I've managed to solve my issue in the following way. Essentially, if the user is logged in, keep the dashboard alive. Else, don't keep the dashboard alive. I check if the user is logged in or out every time the route changes by "watching" the route (see below). If you are reading this and have a more elegant solution - I'd love to hear it.
The following is the code for my root component
<template>
<div id="app">
<!-- if user is logged in, keep dashboard alive -->
<keep-alive
v-bind:include="[ 'dashboard' ]"
v-if="isLoggedIn">
<router-view></router-view>
</keep-alive>
<!-- otherwise don't keep anything alive -->
<router-view v-else></router-view>
</div>
</template>
<script>
import firebase from "firebase";
export default {
name: 'app',
data() {
return {
isLoggedIn: false // determines if dashboard is kept alive or not
}
},
watch: {
$route (to, from){ // if the route changes...
if (firebase.auth().currentUser) { // firebase returns null if user logged out
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
}
}
}
</script>
I had the same problem and I solved it by using an array of cached components and bus event.
Here is my HTML keep-alive App.vue:
<keep-alive :include="cachedComponents">
<router-view></router-view>
</keep-alive>
Here is what I'm doing in the created() life cycle:
created() {
// Push Home component in cached component array if it doesn't exist in the array
if (!this.cachedComponents.includes('Home')) {
this.cachedComponents.push('Home')
}
// Event to remove the components from the cache
bus.$on('clearCachedComponents', (data) => {
// If the received component exist
if (this.cachedComponents.includes(data)) {
// Get the index of the component in the array
const index = this.cachedComponents.indexOf(data)
// Remove it from the array
this.cachedComponents.splice(index, 1)
}
})
}
And inside another component just trigger the event and send the component to remove in parameter.
Another.vue
bus.$emit('clearCachedComponents', 'Home')
If you don't know how to make a bus event there are lot of tutorials on the internet like this to do that. But bus event is my way to do that and you can use everything you want like a child emitter or Vuex. That I want to show is to use an array of components to manage your cache. All you have to do is to add or remove your components in the array.
for anyone looking for a solution that destroys the cache
in my case I was using this in a logout route, replace router.app with this.$root in Vue instances and the $children index/nesting may differ for your app
setTimeout(() => {
var d = [];
for(var vm of router.app.$children[0].$children) {
if(vm._inactive === true)
d.push(vm);
}
for(var vm of d) {
vm.$destroy();
}
});
If your problem is that the component is still holding the old user's data, the only option is resetting it with an internal reset function, which reloads the data for the new user one way or another.
See:
http://jsfiddle.net/paolomioni/hayskdy8/
var Home = Vue.component('Home', {
template: `<div><h1>{{ title }}</h1>
<input type="button" value="click to change text" v-on:click="title = Math.random()"">
<input type="button" value="click to reset component" v-on:click="reset"></div>`,
data: () => {
return {
title: 'BBB'
}
},
methods: {
reset() {
this.title = 'BBB'
}
}
});
In the fiddle, click on the button "change text" to change the text: if you click the checkbox twice to switch view and back again, you will see that the number you've generated is still kept in memory. If you click on the "reset" button, it will be reset to its initial state. You need to implement the reset method on your component and call it programmaticaly when the user logs out or when the new user logs in.

How to allow child component to react to a routing event before the parent component?

I am using react, react-router & redux. The structure of my app is such:
CoreLayout
-> <MaterialToolbar /> (contains back button)
-> {children} (react-router)
When the user presses the back button, which is normally handled by the CoreLayout, I would like the current child component to handle the back button instead of the parent. (In my case, I would like the current view to check if its data has been modified, and pop up an 'Are you sure you wish to cancel?' box before actually going back.) If the child does not wish to handle this, the parent will do it's thing.
Another example would be allowing a childview to set the title in the toolbar.
My reading has told me that accessing a component through a ref and calling a method on it is not the react way -- this is also made a bit more difficult since I am using redux-connect. What is the correct way to implement this behavior?
This is how I would do it, assuming you mean your navigation back button (and not the browser back button):
class CoreLayout extends Component {
handleBack () {
//... use router to go back
}
render () {
return <div>
<MaterialToolbar />
{React.children.map(this.props.children, child => React.cloneElement(child, { onBack: this.handleBack }))}
</div>
}
}
class Child extends Component {
handleBackButtonClick () {
// Here perform the logic to decide what to do
if (dataHasBeenModifiedAndConfirmed) {
// Yes, user wants to go back, call function passed by the parent
this.props.onBack()
} else {
// User didn't confirm, decide what to do
}
}
render () {
return <div onClick={this.handleBackButtonClick.bind(this)}>
Go Back
</div>
}
}
You simply pass a function from the parent to the child via props. Then in the child you can implement the logic to check if you really want to delegate the work to the parent component.
Since you use react-router and your children are passed to your parent component through this.props.children, to pass the onBack function you need to map the children and use React.cloneElement to pass your props (see this answer if you need more details on that: React.cloneElement: pass new children or copy props.children?).
Edit:
Since it seems you want to let the children decide, you can do it this way (using refs):
class CoreLayout extends Component {
constructor () {
super()
this.childRefs = {};
}
handleBack () {
for (let refKey in Object.keys(this.childRefs) {
const refCmp = this.childRefs[refKey];
// You can also pass extra args to refCmp.shouldGoBack if you need to
if (typeof refCmp.shouldGoBack === 'function' && !refCmp.shouldGoBack()) {
return false;
}
}
// No child requested to handle the back button, continue here...
}
render () {
return <div>
<MaterialToolbar />
{React.children.map(this.props.children, (child, n) => React.cloneElement(child, {
ref: cmp => { this.childRefs[n] = cmp; }
}))}
</div>
}
}
class Child extends Component {
shouldGoBack () {
// Return true/false if you do/don't want to actually go back
return true
}
render () {
return <div>
Some content here
</div>
}
}
This is a bit more convoluted as normally with React it's easier/more idiomatic to have a "smart" parent that decides based on the state, but given your specific case (back button in the parent and the logic in the children) and without reimplementing a few other things, I think using refs this way is fine.
Alternatively (with Redux) as the other answer suggested, you would need to set something in the Redux state from the children that you can use in the parent to decide what to do.
Hope it's helpful.
I don't think there is a correct way to solve this problem, but there are many ways. If I understand your problem correctly, most of the time the back button onClick handler will be handled within CoreLayout, but when a particular child is rendered that child will handle the onClick event. This is an interesting problem, because the ability to change the functionality of the back button needs to be globally available, or at very least available in CoreLayout and the particular child component.
I have not used redux, but I have used Fluxible and am familar with the Flux architecture and the pub/sub pattern.
Perhaps you can utilize your redux store to determine the functionality of your back button. And your CoreLayout component would handle rendering the prompt. There is a bug with the following code, but I thought I would not delete my answer for the sake of giving you an idea of what I am talking about and hopefully the following code does that. You would need to think through the logic to get this working correctly, but the idea is there. Use the store to determine what the back button will do.
//Core Layout
componentDidMount() {
store.subscribe(() => {
const state = store.getState();
// backFunction is a string correlating to name of function in Core Layout Component
if(state.backFunction) {
// lets assume backFunction is 'showModal'. Execute this.showModal()
// and let it handle the rest.
this[state.backFunction]();
// set function to false so its not called everytime the store updates.
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: false})
}
})
}
showModal() {
// update state, show modal in Core Layout
if(userWantsToGoBack) {
this.onBack();
// update store backFunction to be the default onBack
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: 'onBack'})
// if they don't want to go back, hide the modal
} else {
// hide modal
}
}
onBack() {
// handle going back when modal doesn't need to be shown
}
The next step is to update your store when the child component mounts
// Child component
componentDidMount(){
// update backFunction so when back button is clicked the appropriate function will be called from CoreLayout
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: 'showModal'});
}
This way you don't need to worry about passing any function to your child component you let the state of the store determine which function CoreLayout will call.

Emberjs: stop and retry transitions in willTransition

When a user is about to leave the present route, I'd like to display a warning and let him choose between leaving (and losing changes) and staying in the current route.
In order to catch all possible transitions, I need to do this in the routes willTransition method.
I'm attempting to abort() and then retry() the transition if the user chooses to. But the retry doesn't seem to have any effect. It should be noted that it is called asynchronously. Here's a twiddle that demonstrates that: https://ember-twiddle.com/b6d8ddb665ff79f2988277912916e77b?openFiles=routes.my-route.js%2C
Here's my route example route:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
willTransition(transition) {
transition.abort();
Ember.run.later(function(){
console.log('Transition... now!');
transition.retry();
}, 2000);
return true;
}
}
});
The log shows up, but I never get redirected to the application route.
Take a look into log. You will see that "Transition... now!" appears there every 2 sec. That shows that willTransition works again and again. So you need some flag that allows you to go away. Updated twiddle
When a user is about to leave the present route, I'd like to display a warning and let him choose between leaving (and losing changes) and staying in the current route.
For the above requirement, the below code is enough.
willTransition(transition) {
if (!confirm('Are you sure to navigate ?')) {
transition.abort();
return false;
}
return true;
}

Categories

Resources