firebase.messaging().setBackgroundMessageHandler(*) 'handler' expected a function - reactjs

Whenever I hot reload my app or an unhandled exception gets thrown and crashes my React Native App, this error message pops up. My index.js has
firebase.messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log(JSON.stringify(remoteMessage));
});

There could be a few reasons for that. It might be possible that JSON.stringify(remoteMessage) is getting crashed and since you have not added catch in your promise chain you are getting the unhandled exception.
Could you modify your code to below:
firebase.messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log(JSON.stringify(remoteMessage));
}).catch(e => {console.log(e)});
And then analyze the crash stack

Related

React Hook Effects Error not able to deploy the website

useEffect(() => {
let val = window.ethereum.isConnected();
if(val)
{
console.log("here");
getAddress();
toggleConnect(val);
updateButton();
}
window.ethereum.on('accountsChanged', function(accounts){
window.location.replace(location.pathname)
})
});
React Hook useEffect contains a call to 'toggleConnect'. Without a list of dependencies, this can lead to an infinite chain of updates. To fix this, pass [location.pathname] as a second argument to the useEffect Hook.
Please, could anyone help with fixing this error?
I tried fixing it by using // eslint-disable-next-line. The warning went away but I am facing issues deploying the website online. It is giving error messages.

Changing state in React causes error 429 with Azure SignalR

I am trying to make a React app with Azure SignalR, using this tutorial as a base. I haven't changed anything about the SignalR server, which can be found here. I'm using the JS version. The app works fine otherwise, but whenever the state changes, requests are sent to SignalR or something along those lines, eventually causing a 429 error. This is the output when state changes once:
[2020-01-09T15:11:42.207Z] Information: Normalizing '/api' to 'http://localhost:3000/api'.
[2020-01-09T15:11:42.437Z] Information: WebSocket connected to wss://bpm-drawing.service.signalr.net/client/?hub=chat&id=5_gylFnC52hduxXnoFT7dgb3b5d12b1&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE1Nzg1ODI3MDIsImV4cCI6MTU3ODU4NDUwMiwiaWF0IjoxNTc4NTgyNzAyLCJhdWQiOiJodHRwczovL2JwbS1kcmF3aW5nLnNlcnZpY2Uuc2lnbmFsci5uZXQvY2xpZW50Lz9odWI9Y2hhdCJ9.byfLiITpaUPm9OLxjn-EN8XcwDT3_j6tdoN2uSdR91k.
[2020-01-09T15:11:42.440Z] Information: Using HubProtocol 'json'.
Enough consequent state changes cause a 429 error. Some of the error messages:
WebSocket connection to 'wss://bpm-drawing.service.signalr.net/client/?hub=chat&id=zer-1PBd58usOkZ2n-3Wuwb3b5d12b1&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE1Nzg1ODI4OTYsImV4cCI6MTU3ODU4NDY5NiwiaWF0IjoxNTc4NTgyODk2LCJhdWQiOiJodHRwczovL2JwbS1kcmF3aW5nLnNlcnZpY2Uuc2lnbmFsci5uZXQvY2xpZW50Lz9odWI9Y2hhdCJ9.t7HPErziiAbQX1PLONvtF3tSHa4ezcBNgAhb0tgNJYA' failed: Error during WebSocket handshake: Unexpected response code: 429
[2020-01-09T15:14:59.060Z] Error: Failed to start the transport 'WebSockets': Error: There was an error with the transport.
POST https://bpm-drawing.service.signalr.net/client/negotiate?hub=chat&negotiateVersion=1 429
[2020-01-09T15:14:59.143Z] Error: Failed to complete negotiation with the server: Error
[2020-01-09T15:14:59.148Z] Error: Failed to start the connection: Error
Errors.ts:20 Uncaught (in promise) Error
at new HttpError (Errors.ts:20)
at XMLHttpRequest.xhr.onload (XhrHttpClient.ts:70)
I stripped my code down quite a bit but this is enough to cause the error:
import React from "react";
const signalR = require("#microsoft/signalr");
export const App = () => {
const [message, setMessage] = React.useState("");
const connection = new signalR.HubConnectionBuilder()
.withUrl(`/api`)
.configureLogging(signalR.LogLevel.Information)
.build();
connection.onclose(() => console.log("disconnected"));
connection.start();
function updateMsg(e) {
e.preventDefault();
setMessage(e.target.value);
}
return (
<div>
<form>
<input
type="text"
placeholder="Type message here..."
onChange={updateMsg}
/>
</form>
</div>
);
};
export default App;
The npm server just has a lot of
[HPM] POST /api/negotiate?negotiateVersion=1 -> http://localhost:7071
Okay so the problem is that the code inside App is run every time state updates, so the connection is formed again. Still haven't figured out quite how to solve it but at least I know what the cause is.
EDIT: Since I was asked, the solution is to put the forming of the connection inside a 'useEffect' hook, so that it's only run once, when the component is mounted.

Nodejs - FindOneAndUpdate method works but makes my website crash (using mongo) on events.js

I want to delete an array index with an ID that I get from front-end. My code works fine and the elements are deleted, however the website crashes and I have to restart npm or check mongo's atlas to check the results. I'm really in the dark here.
Here's the error:
events.js:167
throw er; // Unhandled 'error' event
^
ReferenceError: errors is not defined
at User.findOneAndUpdate (C:\repos\InventoryApp\routes\index.js:52:17)
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4851:16
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4853:13
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
[nodemon] app crashed - waiting for file changes before starting...
//all variables are set and I have done a push method with the same variables
User.findOneAndUpdate(
{ email : useremail },
{ $pull: { products: {
_id : mongoose.Types.ObjectId(id)
} } },
(err) => {
if (err) console.log('found errors');
req.flash('success_msg', 'New record');
})
I found out that mongoose.Types.ObjectId(id) was causing this issue.
By doing _id : id I mananged to make it work.

Error thrown when react component refreshes

I have a react typescript component that has the following componentDidMount method:
componentDidMount() {
ComponentFields.get(this.ComponentName)
.then(activeFields => {
this.setState({ activeFields });
});
}
It has a state interface with following field
export interface ISettingsPageState {
activeFields: Dictionary<IComponentField>,
}
where IComponentField is an interface.ComponentFields.get(componentName: string) is a static method which returns a Promise<IDictionary<IComponentField>>.
It works fine the first time it loads but when I refresh the page, the setState method in componentDidMount throws the following exception:
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
Anyone have any idea what could be causing this?
It turns out that it was a child component throwing the error. Even though the exception was being thrown at the setState line, the problem was in my rendermethod. If anyone has the same problem, I would suggest taking a look at the render method to see what's going wrong.

How to use react-native-i18n in detox[react-native]

I want to test the alert message in detox,and the message use i18n.
const i18n = require("react-native-i18n");
describe("Example", () => {
beforeEach(async () => {
await device.reloadReactNative();
});
it("should show hello screen after tap", async () => {
await element(by.id("btnLogin")).tap();
I18n.t(LocaleKeys.errorMsg_invalidUsername);
await expect(element(by.text(I18n.t(LocaleKeys.errorMsg_invalidUsername)))).toBeVisible();
// await expect(element(by.text("Please input the email and password."))).toBeVisible();
});
});
Run test and get the following error.
Test suite failed to run
/Users/leogeng/Desktop/studentREP/student-app/node_modules/react-native-i18n/index.js:14
export const getLanguages = () => RNI18n.getLanguages();
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (../node_modules/jest-runtime/build/script_transformer.js:305:17)
at Object.<anonymous> (firstTest.spec.js:1:114)
at Generator.next (<anonymous>)
Then I add the following code for jest:
{
"preset": "react-native",
"transformIgnorePatterns": [
"/node_modules/(?!(react-native(.*)?/|native-base(.*)?/|react-navigation/))"
]
}
and get error again:
Validation Error:
Module <rootDir>/node_modules/react-native/jest/setup.js in the setupFiles option was not found.
Actually i confirm 'setup,js' exist in node_modules/react-native/jest.
I do not know why the error happens, anybody can help me?
Thanks
Most likely it's because you're using an old version of node, try to update and see if it solves the issue. Also, it's completely unrelated to Jest and you should probably revert your attempts to modify Jest settings if you don't have any issues with Jest unit tests; in anyway, it will not fix the detox issues.
In case you have some requirement or reason which forces you to keep node at a specific old version, you can bypass it by performing the test differently: have a demo screen only for the e2e tests (or even create a whole demo project just for e2e), in the demo screen you can have a button which performs what you need with i18n (changing locale or whatever), and in the detox test you tap this "demo" button before testing what you actually want.
I've had the same problem. I resolve it by importing i18n-js instead of react-native-i18n.
Because react-native-i18n is not a plain javascript framework, Detox can't import it.
But react-native-i18n is using i18n-js, so you can access your translations without any problem
const I18n = require('i18n-js')
// and then you can use it for your tests
...
await element(by.text( I18n.t('hello') )).tap()

Resources