Why resolve function executed two times in Promise? [duplicate] - javascript

I heard that strict mode helps to write React code in best practices way by throwing warnings for life cycle methods removal. I read about it from this article on Medium.
Is my understanding correct? How effective is strict mode? Is it only for unsafe life cycle methods? If not can I use this feature in functional components?
import { StrictMode } from "react";
class Test extends Component{
render(
<StrictMode>
//Some other child component which has all lifecycle methods implemented in it
</StrictMode>
);
}

React's StrictMode is sort of a helper component that will help you write better React components, you can wrap a set of components with <StrictMode /> and it'll basically:
Verify that the components inside are following some of the recommended practices and warn you if not in the console.
Verify the deprecated methods are not being used, and if they're used strict mode will warn you in the console.
Help you prevent some side effects by identifying potential risks.
As the documentation says, strict mode is development oriented so you don't need to worry about it impacting on your production build.
I've found it especially useful to implement strict mode when I'm working on new code bases and I want to see what kind of code/components I'm facing. Also if you're on bug hunting mode, sometimes it's a good idea to wrap with <StrictMode /> the components/blocks of code you think might be the source of the problem.
So yeah, you're in the correct path to understanding strict mode, keep it up, I think it's one of those things you understand better when you play with them, so go ahead and have some fun.

Warning: StrictMode will render the components twice only on the development
mode not production.
For instance, if you're using getDerivedStateFromProps method like so:
static getDerivedStateFromProps(nextProps, prevState){// it will call twice
if(prevState.name !== nextProps.name){
console.log(`PrevState: ${prevState.name} + nextProps: ${nextProps.name}`)
return { name: nextProps.name }
}
return {}
}
The getDerivedStateFromProps method will call twice.
Just to let you know this is not a problem, it's just because you're wrapping your main component with <StrictMode> in the index.js file.
StrictMode renders components twice in order to detect any problems with your code and warn you about them.

In short, StrictMode helps to identify unsafe, legacy, or deprecated APIs/lifecycles. It's used for highlighting possible problems. Since it's a developer tool, it runs only in development mode. It renders every component inside the web app twice in order to identify and detect any problems in the app and show warning messages.

StrictMode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

Related

Is it necessary to validate react native props?

I am creating a react native app with expo. When I run ESlint, I receive over 100 errors concerning react/prop-types. Most of the errors look like this:
18:37 error 'route' is missing in props validation react/prop-types
I understand that I can validate all of my proptypes with code that looks like this:
import PropTypes from "prop-types";
...
App.propTypes = {
route: PropTypes.object.isRequired,
};
However my app works fine without prop validation (at least, it seems to work fine). Is it necessary to validate all of my props, or can I simply silence the ESlint error without harming my app?
This validation is used to enhance the development process and bug detection.
It doesn't make the app safer directly.
You can disable this option entirely if you don't like it.
Typing is really helpful to understand your code later on and to avoid bugs, but is not required. I personally prefer using Typescript in combination with React. Giving components an Interface makes propTypes obsolete.

findDOMNode is deprecated

On my site (written in React) I use a calendar so that the user can select a date and time range. For this I use the react-advanced-datetimerange-picker library.
Also in index.js file I use <React.StrictMode>. Because of this, when working with the library, I have some warnings. I would like to get rid of them.
I know the easiest way to remove <React.StrictMode>.
But this is not entirely true.
Below is a part of my code
return (
<DateTimeRangeContainer
ranges={ranges}
autoApply={true}
start={time.start}
end={time.end}
local={local}
applyCallback={handleDateRangeChange}
forceMobileMode
years={[2022, 2025]}
style={styleRange}
>
</DateTimeRangeContainer>
);
The whole problem lies in the DateTimeRangeContainer component. If I remove it, the warnings disappear. So here are the warnings I have:
react-dom.development.js:86 Warning: Legacy context API has been detected within a strict-mode tree. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. Please update the following components: FormControl. Learn more about this warning here: https://reactjs.org/link/legacy-context
and second..
react-dom.development.js:86 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of DateTimeRangeContainer which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node
Help me fix them
The issue is most likely because of an older version of react used in the library. One workaround is to use another library or another one is to wait for the author to update the library.
I created an issue on the library repo. Please find it here

importing ConnectButton from web3uikit gives Error: Invalid hook call. Hooks can only be called inside of the body of a function component

I am using nextjs along with tailwind css and a bunch of other libraries like web3uikit.
the app work totally fine but as soon as I import ConnectButton from web3uikit and use it in the sidebar component, it gives me the following error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Here's the link to the github repo, just cloning and install the dependencies would help you in setting up the project and then npm run dev.
Link: https://github.com/oneknucklehead/marketplace-web3
I believe it is a server-side rendering issue! A screenshot of how I got the <ConnectButton /> to render in a nextjs application is below:
Implementing the ConnectButton Component Screenshot
When the error popped up saying I had an invalid hook call, I closed the error box and the button was rendered in and when I click on it, it showed the web3Modal with the proper sign-in options. I thought that maybe it was a server-side issue
So I fixed it by using a useState hook with a boolean value as seen in the screenshot. It is false by default but will only become true when the component loads in(used a useEffect hook to implement) and I take advantage of that via conditional rendering which is also shown in the screenshot. Once I did that, I haven't encountered the issue at all! Hope this helps!
Go to node_modules -> web3uikit-> node_modules and delete the react folder under it.
web3uikit node module has a version of react pre-installed with it. Apparently, that's causing errors. Now, why does deleting the folder fix the error? Honestly, I don't know, but it removed the error. This answer is from someone named David MacDonald.

Why useState calls function twice? [duplicate]

My React Component is rendering twice. So, I decided to do a line-by-line debug, and the problem is here:
if ( workInProgress.mode & StrictMode) {
instance.render();
}
React-dom.development.js
Is it because of the strict mode? Can I disable it? What is Strict Mode? Do I need it?
StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
If you have StrictMode enabled in your app but don't remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.
For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root')
);
If so, you can disable StrictMode by removing the <React.StrictMode> tag:
ReactDOM.render(
{app}
document.getElementById('root')
);
Yes you have to remove Strict mode as
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor , render , and shouldComponentUpdate methods.
Source: React Docs: Strict Mode
For Next.js user here like my-self,
strict mode is also enabled by default and causes this issue.
You can disable it in this way
// next.config.js
module.exports = {
reactStrictMode: false,
}
It seems the component renders twice, but the first rendered component is not unmounted? At least that is the behaviour I'm seeing with React 17, might a bug in my code of course
In a React app with StrictMode:
If you are seeing dual console logs like this:
And if you know that StrictMode helps you optimize your app in some way
And you don't want to disable StrictMode entirely
Then:
The React Developer Tools Chrome Extension offers an option to Hide logs during second render in Strict Mode. To enable that:
Install the extension.
In your Chrome Developer Tools window, a new tab called Components is created. Click on it.
Then click the gear icon inside the components tab.
Then select the Debugging tab, and check the option to Hide logs during second render in Strict Mode.
You will no more see the dual logs in the console.
if you are using nextjs and you want to disable strict mode go to your next.config.js file and set reactStrictMode to false
module.exports = {
reactStrictMode: false,
};
but strict mode is recommended for development once you check if the double mount is caused by stric mode it's preferable to enable it

Unknown props - react and material-ui

Currently I'm using react and material-ui and I've the following code in my component.
<Dialog
title="Dialog With Actions"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}>
Are you sure that you want to proceed?
</Dialog>
I've imported
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
But I'm always getting the following error message
Warning: Unknown prop `onKeyboardFocus` on <button> tag. Remove this prop from the element.
Warning: Unknown prop `keyboardFocused` on <button> tag. Remove this prop from the element.
Use react-tap-event-plugin to resolve this issue. After installing do this -
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
First, this is a warning and not an error message i.e. your code is still working. If you follow the link in the warning message, you can find out that:
The unknown-prop warning will fire if you attempt to render a DOM
element with a prop that is not recognized by React as a legal DOM
attribute/property. You should ensure that your DOM elements do not
have spurious props floating around.
There are more details and the possible reasons, but if I have to speculate you are passing all props to the button element.
Also interesting is a comment bellow the note:
For anyone who is curious/wondering why this new warning exists...
Historically, React has maintained a whitelist of all valid DOM
attributes, and we would strip unrecognized attributes. This approach
has a couple major downsides:
Performance: It means we must do a check for every prop on every DOM element, to sanity check that the prop is valid, and strip the
prop if it is not legal. This is silly, because the majority of
elements are completely safe (no illegal attributes) and thus the
checks are just wasted CPU cycles.
The old technique forced us to maintain a huge whitelist of all possible DOM attributes. This is a pain to maintain, but more
importantly, if we accidentally miss one or browser vendors add a new
one, it means that prop can't be used until we update our whitelist
The old technique is less flexible because it is impossible to render a non-standard attribute. While rendering non-standard
attributes is not recommended (you should use a data- attribute
instead), sometimes there are situations/frameworks that require
it. It sucks that React previously couldn't support it.
As we move toward removing this whitelist, we need to give people an
opportunity to clean up their existing apps. This way, an upgrade
doesn't result in us dumping a ton of unexpected props into the DOM.
EDIT:
Most probably this is coming from the jsx of the library you are using ( material-ui ) Check if you are using the latest version or if you are, they should probably address it soon
This is an issue with material-ui that they've already fixed. Wait for their 0.15.2 release or get their master branch now.

Categories