How to hide componentWillMount warnings - javascript

I'm getting four big warnings that can not be minimized in my console. These warnings are from what I understand not because I have done anything wrong, but because react-router-dom and react-select use the deprecated componentWillMount function. How do I get rid of the warnings?
I have tried looking up the problem on this site, but the closest to a solution I have found is https://stackoverflow.com/a/49166225/12057512. Since the answer is from over a year ago I am wondering if this is still the case. Have these big/popular npm packages still not updated since then?
This is one of the warnings I get (the others are similar):
react-dom.development.js:11494 Warning: componentWillMount has been
renamed, and is not recommended for use. See https:// fb .
me/react-async-component-lifecycle-hooks for details.
Move code with side effects to componentDidMount, and set initial state in the constructor.
Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name
will work. To rename all deprecated lifecycles to their new names, you
can run npx react-codemod rename-unsafe-lifecycles in your project
source folder.
Please update the following components: BrowserRouter, Route, Router,
Switch
(I actually tried to run "npx react-codemod rename-unsafe-lifecycles" but it made no difference)
I have no control over how these npm packages work internally, so I find it frustrating that I constantly get these warnings that I can not fix or remove.

The best I found..
const warn = console.warn;
function logWarning(...warnings){
let showWarning = true;
warnings.forEach(warning => {
if (warning.includes("UNSAFE_")) showWarning = false;
else if (warning.includes("SourceMap")) showWarning = false;
else if (warning.includes("DevTools")) showWarning = false;
});
if(showWarning) warn(...warnings);
}
console.warn = logWarning;

The common way to fix this would be to update the affected libraries (as you say react-router and react-select). If these are being maintained, then they would release new versions that don't produce these warnings. If that is not an option for you, then I don't know, I don't think React has a way of suppressing specific warnings.
Note that the warnings are only shown in the dev build of React, they won't be shown in the production build of React (see DOCs).

JeanMGirard's answer causes Uncaught RangeError: Maximum call stack size exceeded in some instances like when you forget to add dependencies to the dependency array within the useEffect React Hook. This can make it very hard to debug certain bugs in your code.
Normally, React DevTools would handle this by displaying the warning cause and possible solutions.
Here's a solution which ensures React DevTools handles our warnings as normal, but hides the UNSAFE_ warnings:
const backup = console.warn;
console.warn = function filterWarnings(warning) {
// If the warning includes any of the following text, let's hide it.
const supressedWarnings = [
"Warning: componentWillMount has been renamed, and is not recommended for use.",
"Warning: componentWillReceiveProps has been renamed, and is not recommended for use.",
"Warning: componentWillUpdate has been renamed, and is not recommended for use.",
];
if (warning.length && !supressedWarnings.some(entry => warning.includes(entry))) {
backup.apply(console, arguments);
}
};

Use code below:
console.disableYellowBox = true;

In index.android.js, you can use:
console.disableYellowBox = true
console.warn = () => {}

Related

How to make Webpack recognize dynamic exports

I'm seeing the following warning when building with Webpack v4 (using babel-loader for the JS files):
Warning in ./src/components/Foo
"export 'ADDENDUM' was not found in '../../types'
...
The import in ./src/components/Foo is:
import { ADDENDUM } from '../../types';
../../types:
import { each } from 'lodash';
export const typesDict = {
ADDENDUM: 'addendum',
};
each(typesDict, (type, typeConstant) => {
exports[typeConstant] = type;
});
This isn't causing a build error, just a warning. The warning is wrong though, since I am exporting ADDENDUM (though dynamically), and everything works as it should.
Is there a way for Webpack to handle these dynamic imports, or to at least turn off the warning? I'm upgrading from Webpack v1 right now, and v1 does not have this problem (or if it does, it's being hidden somehow).
Also please note: I do NOT want to silence all Webpack warnings, such as via the devServer config. I just want to silence this one type of warning.
Based on your ../../types file i assume your approach was to skip writing again the components in the exports object.
Instead of silencing the warning, try something simpler to fix the issue. Since you don't want to write twice the same names, take a look at my example.
No lodash is required, no loops are used and exported constants are written once.
../../types:
export const ADDENDUM = 'addendum';
export const ADDENDUM2 = 'addendum2';
export const ADDENDUM3 = 'addendum3';
That is all, no more dynamic imports, no more warnings.
UPDATE:
Your code is indeed valid, but when you use dynamic exports/imports, compilers/bundlers loose trace of your exports(in your case) since they don't check the contents of your exports object, thus the warning you receive, because the compiler(babel) didn't find exports.ADDENDUM in your code, only you know that it's there, therefore the compiler thinks you're using an unexisting component.
As of imports, it's the same story, the same type of warning was emitted by webpack when something like require('/path/to/' + someVar + '/some.file.js'), because webpack wanted to make a chunk out of it, but that wasn't a full path for webpack and it couldn't find the file because it was a concatenated string (dynamic import). (i don't know if this changed over the years, but i'm sure you understand/knew this perfectly well too)

Using Cucumber.js with Jest

I am using Jest for my unit tests and I'm in the process of integrating Cucumber.js for running specs written in Gherkin.
I have it all set up and it's working, but I am running into one problem: How can I use Jest's expect? I could use chai's, but I'd like to keep the expect syntax the same between my unit tests and my step definitions (I don't want to.equal in my step definitions and toEqual in my unit tests).
How can I do that? After some digging it seems as if Jest relies on the expect npm package. I could depend on that package explicitly in my package.json, but I'd much rather use my existing Jest dependency. Maybe that's not possible, but I hope it is.
Another option would be to somehow execute the Gherkin specs with the Jest test-runner. I'd be open to that option as well. At the moment I'm running them by calling cucumber.js separately from my Jest test-runner.
My react-native environment:
"cucumber": "^4.1.0",
"jest": "22.4.2",
In my steps definition file, I just require it like this
const { Given, Then, When } = require('cucumber');
const expect = require('expect');
Expect is part of Jest, so you can import it as its own object. Then I can use it wherever I need an assertion. Note: newMember is declared and populated elsewhere.
Given('Sara has provided account details', function() {
for (const prop in newMember) {
expect(newMember[prop]).toBeTruthy();
}
});
Hope that helps.
expect is a globally scoped during jest runtime. So as long as you are running jest it will be available. I'm using this package (needs some config to transform correctly to your babel config): gherkin-jest
Here's a feature using the DOM-testing example from the jest docs:
Feature: Using feature files in jest and cucumber
As a developer
I want to write tests in cucumber and jest
So that businesspeople understand tests and I can test React
Scenario: Emoji toggles upon checking and unchecking the checkbox
Given I did not check the checkbox, so the label is "😭"
When I check the box and the emoji toggles to be "😎"
import {cucumber as c} from 'gherkin-jest'
import React from 'react'
import {mount} from 'enzyme'
import {Checkbox} from '../src/components'
c.defineCreateWorld(() => ({
checkbox:null
}))
c.defineRule('I did not check the checkbox so the label is {string}', (world, off) => {
world.checkbox = mount(<Checkbox labelOff={off} />)
expect(world.checkbox.text()).toBe(off)
})
c.defineRule('I checked the box and the emoji toggles to be {string}', (world, on) =>{
world.checkbox = mount(<Checkbox labelOn={on}/>)
world.checkbox.find('TouchableOpacity').props().onPress()
expect(world.checkbox.text()).toBe(on)
})
This issue I posted gives an example of the config.
An alternative would be to use jest-cucumber
https://www.npmjs.com/package/jest-cucumber.
gives you the flexibility of using both frameworks

React Native imports not working after upgrade

Hi I've been in charge of an old React-Native iOS project and I need to upgrade its React-Native from 0.25.1 to 0.48.0 but I'm running into a lot of compiler issues and can't figure out how to update the code.
I have an index.ios.js file that looks like this:
var ReactNative = require('react-native');
var ResumeIns = require('./resume_ins_controller');
ReactNative.AppRegistry.registerComponent('ResumeInsController', () => ResumeIns.Navigation);
A resume_ins_controller.js in the root folder that looks like this:
var React = require('react');
var EntryManager = require('./entry_manager.js');
class ResumeInsNavigation extends React.Component {
//....
}
and an entry_manager.js in the root folder that looks like this:
class EntryManager {
//....
}
module.exports = EntryManager;
This code worked OK before the upgrade, but now I get this error:
Super expression must either be null or a function, not undefined
and the stack trace points to this line:
module.exports = EntryManager;
Does anyone know how to get this code working for React-Native 0.48?
There's been a ton of changes since 0.25.1. Knowing how painful updates can get, I'd suggest either:
In case of a very complex app: to update RN version by version with the help of release notes, and rn-diff if necessary.
In case of a fairly simple app: to start a new RN project from scratch, and move the app's logic over there.
Either way it would be a good idea to move to ES2015 imports for clarity on named vs default imports as the issue that you're describing is likely caused by the way things are imported, see v0.25.1 deprecations + a link to codemod that may help.
Good luck!

react-konva warning 'Konva' is not defined

I'm trying to learn how to use the canvas in react via a package called react-konva. npm installation was simple enough, and I added some demo code that works...
// in MainComponent.js
import {Stage, Layer, Rect} from 'react-konva';
// in render()
<Stage width={700} height={70}>
<Layer fill={'red'}>
<Rect ... and so on
My code mentions Konva in the context of getting a color...
Konva.Util.getRandomColor()
but my browser warns appropriately: "warning 'Konva' is not defined". I tried this...
import {Konva, Stage, ... } from 'react-konva';
but that makes things worse, generating undefined errors wherever I try to use Konva.. I tried adding a reference directly to konva...
// in index.js
<script src="https://cdn.rawgit.com/konvajs/konva/1.3.0/konva.js"></script>
but then I get this error:
Konva instance is already exist in current eviroment. Please use only
one instance.
(grammar error and misspellings in the original error message)
Would appreciate a pointer, or any thoughts about what might be causing this.
Try to use const Konva= window.Konva
this will allow you use vanilla KonvaJS properties.
As per the comment in your question. You have forgotten to do npm install konva.

Make react-router not break Jest (reactJs) tests

I'm currently trying to add Jest tests to a React application (found here).
However, when I run the following test,
/** #jsx React.DOM */
jest.dontMock('jquery');
jest.dontMock('../js/components/CategoryPage.jsx');
describe('Category Page', function() {
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var CategoryPage = require('../js/components/CategoryPage.jsx');
it('renders into the page correctly', function() {
// Render the CategoryPage into the document
var categoryPage = TestUtils.renderIntoDocument(
<CategoryPage params={{"category": "tests"}} />
);
expect(categoryPage).toBeDefined();
});
});
I get the following error:
● Category Page › it renders into the page correctly
- TypeError: Property 'makeHref' of object #<Object> is not a function
at Navigation.makeHref (/home/stephen/reps/node_modules/react- router/modules/mixins/Navigation.js:29:25)
at React.createClass.getHref (/home/stephen/reps/node_modules/react-router/modules/components/Link.js:76:17)
at React.createClass.render (/home/stephen/reps/node_modules/react-router/modules/components/Link.js:97:18)
at ReactCompositeComponentMixin._renderValidatedComponent (/home/stephen/reps/node_modules/react/lib/ReactCompositeComponent.js:1260:34)
at wrapper [as _renderValidatedComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactCompositeComponentMixin.mountComponent (/home/stephen/reps/node_modules/react/lib/ReactCompositeComponent.js:802:14)
at wrapper [as mountComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/home/stephen/reps/node_modules/react/lib/ReactMultiChild.js:195:42)
at ReactDOMComponent.Mixin._createContentMarkup (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:260:32)
at ReactDOMComponent.Mixin.mountComponent (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:182:14)
at ReactDOMComponent.wrapper [as mountComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/home/stephen/reps/node_modules/react/lib/ReactMultiChild.js:195:42)
at ReactDOMComponent.Mixin._createContentMarkup (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:260:32)
Both my app and the CategoryPage component specifically use react-router. The CategoryPage contains a mixin which uses react-router for authentication. Based on my own debugging, I have found that the error is occurring when Jest tries to call makeHref, one of react-router's built-in methods for Navigation.
To fix this, I first tried calling jest.dontMock('react-router'), but this did not have any effect. The problem seems to be that, by not mocking CategoryPage, jest will automatically and irreversibly include all of its dependecies, unmocked.
Part of the reason this issue is so difficult to solve is because most people using Jest with React seem to not be testing their components, either because they are not as test-focused or because they are using Flux and only testing Stores, Dispatchers, etc. We are not yet using Flux, so this is not an option for us, but may be something we have to transition to in the future.
EDIT 1: The test passes if I remove the jest.dontMock('../js/components/CategoryPage.jsx') but then it is impossible to actually test the functionality of that component.
EDIT 2: When I exclude jest.dontMock('jquery') I get another error related to the mixin I use to create Modals:
Category Page › it encountered a declaration exception
- TypeError:
/home/stephen/reps/js/components/CategoryPage.jsx:
/home/stephen/reps/js/components/Feed.jsx:
/home/stephen/reps/js/components/InvestmentButton.jsx:
/home/stephen/reps/js/components/Modal.jsx:
/home/stephen/reps/js/mixins/BootstrapModalMixin.jsx:
/home/stephen/reps/node_modules/bootstrap/dist/js/npm.js:
/home/stephen/reps/node_modules/bootstrap/js/alert.js: Cannot call method 'on' of undefined
EDIT 3: I have seemingly isolated the bug to react-router's Navigation mixin, where it calls this.context.makeHref. The React team has deprecated this.context since version .9 so I believe this may be the source of the problems. Thus, any work-around or fix for this.context is welcome.
I went ahead and put together a fix which allows you to still use Jest.
https://labs.chie.do/jest-testing-with-react-router/
I ended up figuring this out with some help from the creator of rackt-router after creating the issue found here: https://github.com/rackt/react-router/issues/465 .
I got around this by using Karma and Jasmine to test my application. I then used the stub function makeStubbedDescriptor found here: https://gist.github.com/rpflorence/1f72da0cd9e507ebec29.

Categories