ReactJS console.log disappearing after some second - reactjs

I am implementing SSO in my reactjs app on a button click and debugging one error by adding console.log to see the this.props.location variable. But as I click on the auth me button (that will trigger the sso auth) it shows the log for few second and then disappear. I have taken printscreen
I want to expand the object in console and view the attributes value , but unable to do it as it is disappearing. I have added wait timers also to hold the block but its getting hanged. Is there is a better way so that I can log the console.log's data to a file and view the errors peacefully without getting in a rush.

You have to use this code inside your submit button to prevent the default submit event.
onSubmitClicked = (e) => {
e.preventDefault()
//additional codes
}

Related

Confirmation on browser back button

I'm trying to achieve the following with Gatsby
The user is on a form page, if they hit the browser back button, a pop up would appear, asking if they want to leave.
If the user selects ok, then it would go back.
If the user selects cancel, then it would stay on this page
I was able to "almost" make it happen by doing the following
useEffect(() => {
const confirmExit = e => {
const leaveThisPage = window.confirm("Would you like to leave this page?")
if (!leaveThisPage) {
window.history.forward()
}
}
window.addEventListener("popstate", confirmExit)
return () => {
window.removeEventListener("popstate", confirmExit)
}
}, [])
There is one issue, if the user selects cancel, then the browser would go to the previous page. Then window.history.forward() would fire and sends them back.
I noticed that popstate event cannot be cancelled, so e.preventDefault() won't work.
Note: I also tried to test with window.onbeforeunload, but it only triggers if I close to window, or if my previous is from outside my app. Is there a work around for my issue?
Gatsby is using #reach/router under the hood, which doesn't support intercepting and preventing navigation (emphasis mine):
No history blocking. I found that the only use-case I had was preventing the user from navigating away from a half-filled out form. Not only is it pretty easy to just save the form state to session storage and bring it back when they return, but history blocking doesn’t happen when you navigate away from the app (say to another domain). This kept me from actually using history blocking and always opting to save the form state to session storage. (Source)
I second the recommendation for saving the form state using localStorage.

Clicking a reach dropdown in testcafe

I'm using testcafe in a React app and I'm having some trouble with making testcafe click a dropdown option from a Reach dropdown menu.
I can access the option with Selector after triggering a click on the button that activates the dropdown menu, but clicking the desired option doesn't seem to do anything at all.
However, the action is triggered if I reach the option via keys.
//This works
await t
.click('[testid="menuButton"]')
.pressKey('down')
.pressKey('down')
.pressKey('enter');
//This doesn't
await t
.click('[testid="menuButton"]')
.click('[data-reach-menu-item]:nth-of-type(3)');
I made sure that the selection is made properly in the second case, so that doesn't seem to be the problem.
Any thoughts?
Thanks!
This test is successfully executed on my side:
import { Selector } from 'testcafe';
fixture `fixture 1`
.page `https://reacttraining.com/reach-ui/menu-button/`
test('test', async t => {
await t
.click('[data-reach-menu-button]')
.click('[data-reach-menu-item]:nth-of-type(3)');
})
Perhaps there is more than one menu button on your page, so the '[data-reach-menu-item]:nth-of-type(3)' selector points to an invisible item. To check this, insert .debug() after .click('[testid="menuButton"]') in you code:
await t
.click('[testid="menuButton"]')
.debug()
.click('[data-reach-menu-item]:nth-of-type(3)');
After the test code stops at debug(), open the browser's development console, execute the document.querySelectorAll('[data-reach-menu-item]:nth-of-type(3)') command, and check if the first returned node matches the third element in the menu's dropdown.

ReactJS Function Components object updates on second time

I have a login page(Functional Component), When a user tries to login without entering the required fields, I have to show the error message(ex:"Email is required"). When an invalid field exists, I shouldn't make the API call.
But, without entering fields, when I click on login button, API call is done. Again clicking on login button stops the API call.
I have made this demo - https://stackblitz.com/edit/react-pd6vvk?file=login.js which explains the issue.
Steps to follow:
1.Click on login without filling any text values. You can see "API request made" statement when fields are invalid.
2.Again click on login button, "API Request stopped" statement is displayed now.
I am new to React and I don't know, the reason and the solution to fix this issue.
Can somebody please help me out?
Thank you,
Abhilash
Because, setValidFields has async behaviour :
validateLoginForm(); //<--- inside this setValidFieldsis async
console.log(validFields);
if (isFormValid()) { //<---- so,this will still have true value ( means not updated )
// inside validateLoginForm()
// this state change won,t be reflected immediately
setValidFields(validFields => ({
...validFields,
[key]: error.length == 0
}));
I have made few changes as per your code structure, as long as I know you will need useEffect also as shown in working demo.
WORKING DEMO

React-Router v4 - Prevent Transition With Function

I was able to prevent navigation as per the v4 docs, but I'm trying to hook up a function so that I can use a modal instead of an alert.
Function:
abandonForm = (route) => {
this.props.showModal('confirm');
console.log('leaving..');
}
In my page:
<NavigationPrompt when={true} message={(location) => this.abandonForm('confirm')} />
this.props.showModal('confirm') activates the modal successfully, but behind the modal the page still transitions - how can I prevent transition until a button in the modal is clicked?
Browsers only allow navigation cancellation by means of the alert box that you've mentioned. This restriction is motivated by phishing/scamming sites that try to use javascript gimmicks to create user experiences that convincingly mimic something that a browser or the OS would do (whom the user trusts). Even the format of the text shown in the alert box is crafted so that it's obvious that it originates from the site.
Of course, as long as the current URL stays within your app, you have control over it using react-router's history. For example you can do the following on navigation:
allow the navigation without confirmation
immediately navigate back to the previous location, but now with a modal on top
navigate away for real this time when the user clicks on a button in the modal.
The disadvantage of this approach (leaving out the sheer complexity of it) is that the user will not get a confirmation dialog if they try to navigate to a different site entirely.
Use:
this.unBlock = this.props.history.block((location, navigateToSelectedRoute) => {
// save navigateToSelectedRoute eg this.navigateToSelectedRoute =
// navigateToSelectedRoute;
// use this.navigateToSelectedRoute() afterwards to navigate to link
// show custom modal using setState
});
and when unblocking is done then call this.unBlock() to remove the listener.
Documentation here for history api

cordova back button event conflicting with browser history

I am making a cordova app, using angularjs and ui-router , the problem is when i use the cordova back button event ,my app doesn't go to the previous page, but if i comment the back button event everything works fine , i want to track the back button event but its seems not to work for me , i tried the below code also doesn't seems to help me.
document.addEventListener("backbutton", (e) => {
e.preventDefault();
e.stopPropagation();
}, true);
please help me with the issue
e.preventDefault() as it's name suggests prevents the default behaviour. Therefore you stay on the same page.
If you want to control route switches / state switches imho it's better to listen for the stateChangeStart event. There you can also prevent state changes and you have the extra bonus of knowing which state it came from and where it's going.

Resources