Error in React app: window.functionFromThirdParty is not a function - javascript

From a third party I have to add a function to the window object:
In my React child component I added it like:
useEffect(() => {
window.functionFromThirdParty();
}, [id]);
But then I get this error:
Uncaught TypeError: window.functionFromThirdParty is not a function
How to fix this issue?

Make sure that the function is actually being added to the window object by the third party code. You can check this by running console.log(window) in the browser's developer console and seeing if the function is listed.

It is either related to third party conflict, or you did not import that function properly, could you try to give us more info and specifically where you imported it into window object.

Related

I am getting multiple hydration errors but cannot find the source

I am currently attempting to render the 'Swap' page for my DApp made with nextjs and hardhat. Upon navigating to the 'Swap' page I get the error message:
Application error: a client-side exception has occurred (see the browser console for more information).
Along with the following console errors:
Error: Invalid curve
at a (de297ff1-5db1172d27bc5a6f.js:6:84940)
at new g (de297ff1-5db1172d27bc5a6f.js:15:2181)
at Object.get [as secp256k1] (de297ff1-5db1172d27bc5a6f.js:15:2373)
etc.
A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred
Uncaught Error: Minified React error #418; visit https://reactjs.org/docs/error-decoder.html?invariant=418 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
Uncaught Error: Minified React error #423; visit https://reactjs.org/docs/error-decoder.html?invariant=423 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
Minified React error #418 represents the following error:
Hydration failed because the initial UI does not match what was rendered on the server.
Minified React error #423 represents the following error:
There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
I am still new to coding however it does not appear to me that there is an obvious problem with my jsx being improperly mounted.
I will attach the GitHub repository bellow. In order to access the 'Swap' page navigate to pages/Swap. I've been trying to solve this error for 24 hours now with no luck. Any help would be much appreciated.
https://github.com/BeauC2481/dao
In general, this issue is caused by using a specific library or application code that is relying on something that could differ between pre-rendering and the browser. An example of this is using window in a component's rendering.
An example:
function MyComponent() {
// This condition depends on `window`. During the first render of the browser the `color` variable will be different
const color = typeof window !== 'undefined' ? 'red' : 'blue'
// As color is passed as a prop there is a mismatch between what was rendered server-side vs what was rendered in the first render
return <h1 className={`title ${color}`}>Hello World!</h1>
}
How to fix:
// In order to prevent the first render from being different you can use `useEffect` which is only executed in the browser and is executed during hydration
import { useEffect, useState } from 'react'
function MyComponent() {
// The default value is 'blue', it will be used during pre-rendering and the first render in the browser (hydration)
const [color, setColor] = useState('blue')
// During hydration `useEffect` is called. `window` is available in `useEffect`. In this case because we know we're in the browser checking for window is not needed. If you need to read something from window that is fine.
// By calling `setColor` in `useEffect` a render is triggered after hydrating, this causes the "browser specific" value to be available. In this case 'red'.
useEffect(() => setColor('red'), [])
// As color is a state passed as a prop there is no mismatch between what was rendered server-side vs what was rendered in the first render. After useEffect runs the color is set to 'red'
return <h1 className={`title ${color}`}>Hello World!</h1>
}

Uncaught ReferenceError When Trying to Use Imported React Selector in React actions file

What I want to do: I want to use a state value in one of my action methods.
How I would prefer to do it: Instead of typing out state.sale.oliver.data, I want to obfuscate that by calling my selector, showingTest(state).
Problem: Inside my if statement, the value is undefined, and when I use the browser to log the method name. I get an uncaught reference error.
At the top of my actions.js (which is in the same directory as selectors.js)
actions.js
import { showingTest } from './selectors';
In the same file I have a method and inside the method have the following if statement:
if (showingTest(state).length >= 3)
My code will never go into this if statement,
but if I type
if (state.sale.oliver.data.length >= 3)
then bingo we are working.
Also for reference we have here my selector:
selectors.js
export const showingTest = state => {
return state.sale.oliver.data ? state.sale.oliver.data : "";
}
Ahhh, so here was the issue. I was facing a bug and thinking that my first if statement wasnt working. I was debugging on google chrome and typed that method into the console and there was an uncaught reference error, but when I console.log the value I am indeed accessing the selector.

React Navigation (5+) navigation.addListener() in Class Components

I want to add a Listener beforeRemove to a navigation to prevent the user from going back.
Then they get an alert to proceed or discard.
I followed the tutorial from reactnaviagtion.org but this is in an functional Component.
In my Case its an react-native Class-Component.
I can easily call the function over the props:
componentDidMount(){
this.props.navigation.addListener("beforeRemove", (e) =>{
console.log("beforeRemoveTriggered");
this.state.SomeVariablesToCheckIfGameStarted
Alert.alert(..., onPress: ()=> this.props.navigation.dispatch(e.data.action));
}
}
The console.log is no problem but I can't call the state inside of the callback.
beforeRemoveTriggered
But after that I get the following error:
TypeError: undefined is not an object (evaluating '_this2.props.someVariablesToCheckIfGameStarted`)
- node_modules\...
My Guess is that you cant call the state inside of the listener-callback.
But this is neccessary for the app function so i cant "just dont use the state".
BTW a workaround with useEffect would be accetable but is not preferred.
This may have a simple solution which is not specific with react-navigation or react-native but javascript.
Any tips would be helpful, thanks in advance!!!
I know my answer...
Maybe but just maybe I called this.props instead of this.state
And maybe after this discovery everything works as it should be...
I`m sorry to everyone I bothered figuring out what the solution is!

How to get rid of Error in v-on handler: "TypeError: _vm.myFcn is not a function"?

Following the documentation, I have written a Vue component containing the following logic:
import debounce from 'lodash/debounce'
export default {
[...]
created () {
this.debouncedOnSubmit = debounce(this.doSubmit, 1000)
},
[...]
The idea behind this is that my form calls the debouncedOnSubmit method upon form submission:
<button
name="order-basket"
type="submit"
#click.prevent="debouncedOnSubmit"
>
Click me!
</button>
Now, that code works fine in my application, as well as in my jest tests. For example, with the vue test utils, I can trigger the click event on that button and the relevant stuff that should happen upon clicking that button can be verified successfully.
However, I get the following annoying warning:
[Vue warn]: Error in v-on handler: "TypeError: _vm.debouncedOnSubmit is not a function"
I partially understand why I get that warning. Indeed, I define this.debouncedOnSubmit in the created() hook. It's pretty likely that Jest does not understand the meaning of that variable, even though the debounce method returns a function.
How can make jest understand that debouncedOnSubmit is a function? What do I need to configure?
I do not want to disable the warnings, as explained here, because I do want to keep a feedback on my doings in my tests. Most of time, the warnings are really helpful and I do not feel comfortable with the idea of switching them off. How can I write my code so that this warning is fixed?
EDIT
changing
#click.prevent="debouncedOnSubmit"
to
#click.prevent="debouncedOnSubmit()"
does not change anything to the problem
moving debouncedOnSubmit from the created() hook to the computed stuff like this
debouncedOnSubmit: debounce(this.doSubmit, 1000)
throws the error
TypeError: Cannot read property 'doSubmit' of undefined
changing
#click.prevent="debouncedOnSubmit"
to
#click.prevent="debouncedOnSubmit()"
and moving debouncedOnSubmit from the created() hook to the computed stuff like this
debouncedOnSubmit () {
const submit = this.doSubmit
return debounce(submit, 1000)
}
still makes my app and tests work, but I still end up with the same warning in my jest tests:
[Vue warn]: Error in v-on handler: "TypeError: _vm.debouncedOnSubmit is not a function"
Use methods property to define your functions
methods: {
debouncedOnSubmit()
}
"TypeError: _vm.debouncedOnSubmit is not a function" means vuejs can not find any function in it's build-in functions with this name.
one thing that you miss is just putting your function in Default Components Options like:
methods, computed, actions
methods: {
debouncedOnSubmit () {
const submit = this.doSubmit
return debounce(submit, 1000)
}
}
then you can call your function without error

react componentDidMount not firing

I set up a new react project and for some reason, the componentDidMount method is not being called.
I have verified this behavior by placing a call to console.log in componentDidMount but I cannot see its output in the console.
Furthermore, this.setState() is not working.
I'm pretty stumped as to why the componentDidMount is not being called. I tried using both React "v0.14.0" and "v0.14.3".
Why is 'componentDidMount' not being called?
Code:
var React = require('react');
var RecipePage = React.createClass({
componentDidMount: function() {
console.log('mounted!');
},
render: function() {
return (
<div>Random Page</div>
);
}
});
module.exports = RecipePage;
This happened to me when I had componentWillMount() defined 2x in the same class. This did not produce a runtime error. I simply removed the second definition and things started working.
So... lo and behold.... I finally got it working(with the help of a back-end expert). The reason why the "componentDidMount" methods weren't firing was because my server was bundling and serving all the react + html stuff on server side. (Only "render" and "getInitialState" methods get called to create the "html" template that gets delivered through the client's browser...but it stops there because it thinks it's finished)
The fix: Find a way to deliver the resulting "compiled" html through the server AND in addition, allow react's own events to be accessible and "fireable" again on the client side. When compiling my "view" file( index.js or index.html ), I included an "Application.start()" script that injects my bundle.js code into the template again. Then in my gulpfile, exported the "Application" variable so the "view" file can access it.
Gahh...pulled my hair out for this. Time to read up on server side vs. client side rendering
In my case, there was another componentDidMount earlier in the code
I have the create-react-app template. I added the ComponentDidMount into the App Component. I put a console.log and an alert into it. It does not fire and there are no errors in React or the browser. I tried in chrome and firefox.
FIX: what worked for me was rebooting my pc. Then it started working. I do not know why, but this resolve the issue.
Update: Not I have an uppercase 'C' it is 'componentDidMount' not 'ComponentDidMount'.. I think it's time for sleep.
In my case, I call componentDidMount() for retrieving data from a service (API call) and on the render function I have components that are supposed to use the data that is returned from this call.
But because the call is Async the render() function is called immediately and then it crashes (many errors like: "TypeError:cannot read property 'XXXX' of undefined" ) then it looks like componentDidMount is not called at all.
To solve this issue I check on render that myData !== null before returning the component itself - You can use generic loader\spinner on this case that will not render internal components that use data before the data that actually retrieve from service.
Example:
componentDidMount() {
const { GetMyDataFromServiceFunc } = this.props;
GetMyDataFromServiceFunc ("150288");
}
render() {
const { details, loading } = this.props;
if (!details)
return (<GenericLoader />);
return (
<FullScreenModal
<Wizard className="order-new-wizard">
<Component1 editable={false} dataToComponent1={details}
goNextStep={this.goNextStep} />
<Component2 values={details.customerDetail} goNextStep={this.goNextStep} />
</Wizard>
</FullScreenModal>
);
}
}
You need to change your module.exports to point at RecipePage not TestPage
module.exports = RecipePage;
For me, the reason was upper case "C" in ComponentDidMount.
Changed it to componentDidMount and it worked
For me I also declared componentDidUpdate in the class after that componentDidMount started firing as expected.
Although you have a console log statement in your componentDidMount function it may not be executing because that function never gets run. If the error occurs before componentDidMount gets called such as in your render function, you won't see the console log. Try commenting out the code in your render function and see if it appears.
In my case, I imported a component without the export default command in the imported file. When I fixed this, componentDidMount started firing...
For me, I had onComponentDidMount() instead of componentDidMount() facepalm
componentDidMount did not fire for me because I mistakenly called it twice. Also, it will not show any console error. Removing one of them worked perfectly.

Categories