how do I instantiate web3 for my typescript project? - web3js

please, I am working on a project with typescript and vite, and I need to load web3.js but it is failing to instantiate.
This is the code I used below
import Web3 from 'web3'
const loadWeb3 = async () => { web3 = new Web3(window.ethereum); await window.ethereum.enable(); };
then the error it gives me is as follows:
`util.js:109 Uncaught ReferenceError: process is not defined
at node_modules/util/util.js (util.js:109:1)
at __require2 (chunk-JXMXRRTK.js?v=cedb61c3:35:50)
at node_modules/web3-core-requestmanager/lib/index.js (index.js:20:25)
at __require2 (chunk-JXMXRRTK.js?v=cedb61c3:35:50)
at node_modules/web3-core/lib/index.js (index.js:22:24)
at __require2 (chunk-JXMXRRTK.js?v=cedb61c3:35:50)
at node_modules/web3/lib/index.js (index.js:29:12)
at __require2 (chunk-JXMXRRTK.js?v=cedb61c3:35:50)
at dep:web3:1:16`

Related

Uncaught (in promise) Error: Error: Adapter 'http' is not available in the build

I am trying to use axios in React chrome extension module, but I am facing this issue.
Uncaught (in promise) Error: Error: Adapter 'http' is not available in the build
// background.ts
import axios from "axios"
...
axios.get<SerInyResponse>("https://realtor.p.rapidapi.com/locations/v2/auto-complete")
.then(response => {
this.Storage.setLocalStorage(response.data).then( (re) => {
resolve(response.data.Listeners)
})
})
.catch( err => {
reject(new Error(err))
})
Can anyone help me?

React Native Jest Test TypeError: _reactNative.Linking.addEventListener is not a function

As the title states I'm getting a weird error with the default jest test that is included in a React Native fresh install. The actual test:
import 'react-native';
import React from 'react';
import App from '../src/App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
My jest.setup.js:
// as supplied by the react navigation testing docs
import 'react-native-gesture-handler/jestSetup';
// Mock Ionicons pack
jest.mock('react-native-vector-icons/Ionicons', () => 'Icon');
// Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing
jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
My babel.config.js:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
Then I just try to run npm test (i.e. jest), and I get the following errors:
npm test
> optionscreener#0.0.1 test
> jest
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at Object.prefixes [as Linking] (node_modules/react-native/index.js:320:12)
at subscribe (node_modules/#react-navigation/native/src/useLinking.native.tsx:104:36)
at node_modules/#react-navigation/native/lib/commonjs/useLinking.native.js:183:12
at commitHookEffectListMount (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12932:26)
at commitPassiveMountOnFiber (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14346:11)
at commitPassiveMountEffects_complete (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14306:9)
at commitPassiveMountEffects_begin (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14293:7)
at commitPassiveMountEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14281:3)
at flushPassiveEffectsImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16233:3)
at flushPassiveEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16182:14)
at node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16002:9
at workLoop (node_modules/scheduler/cjs/scheduler.development.js:266:34)
at flushWork (node_modules/scheduler/cjs/scheduler.development.js:239:14)
at Immediate.performWorkUntilDeadline [as _onImmediate] (node_modules/scheduler/cjs/scheduler.development.js:533:21)
RUNS __tests__/App-test.tsx
/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2608
throw error;
^
TypeError: _reactNative.Linking.addEventListener is not a function
at subscribe (/Users/chris/enterprise/OptionScreener/node_modules/#react-navigation/native/src/useLinking.native.tsx:104:45)
at /Users/chris/enterprise/OptionScreener/node_modules/#react-navigation/native/lib/commonjs/useLinking.native.js:183:12
at commitHookEffectListMount (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12932:26)
at commitPassiveMountOnFiber (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14346:11)
at commitPassiveMountEffects_complete (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14306:9)
at commitPassiveMountEffects_begin (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14293:7)
at commitPassiveMountEffects (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14281:3)
at flushPassiveEffectsImpl (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16233:3)
at flushPassiveEffects (/Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16182:14)
at /Users/chris/enterprise/OptionScreener/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16002:9
Node.js v18.12.1
Just once I wish Jest and React Native would play nicely. But, once again, not today. Does anyone have any ideas as to what could be going wrong?
Can you try using jest.useFakeTimers in your jest.setup.js
It’s just a guess but can you give it a try?
If this doesn‘t work can you change the implementation of AppState from:
componentDidMount() {
AppState.addEventListener(
'change',
this._handleAppStateChange
);
}
componentWillUnmount() {
AppState.removeEventListener(
'change',
this._handleAppStateChange
);
}
To the new version:
useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {});
return () => {
subscription.remove();
};
}, []);

Cordova OneSignal Sdk not working in React Capacitor Project

I'm getting this error
TypeError: window.OneSignal.push is not a function
in the latest SDK and Cordova plugin. But when I downgraded the onesignal-cordova-plugin to 2.11.3 I get a plugin_not_installed error.
import React from "react";
import { OneSignal } from "#awesome-cordova-plugins/onesignal";
React.useEffect(()=> {
OneSignalInit();
}, [])
const OneSignalInit = async () => {
OneSignal.startInit(import.meta.env.VITE_ONESIGNAL_APPID, import.meta.env.VITE_GOOGLE_PROJECT_ID); // Error: TypeError: window.OneSignal.push is not a function
};
Package JSON:

import 'useAuthenticator' from aws-amplify outputs "TypeError: window.URL.createObjectURL is not a function" when jest testing

I would like to know how to mock this kind of dependency's error. If I omit this import and comment out related source code, the test process is going to be fine. Already have got through Mock Function Jest, but no idea what I should do.
*This project was created by CRA with template typescript.
App component.
import { useAuthenticator } from '#aws-amplify/ui-react';
const App = () => {
const { user } = useAuthenticator((context) => [context.user]);
return (
<div>{user?.username}</div>
);
};
export default App;
Test code here.
import App from 'src/App';
import { render, screen } from '#testing-library/react';
describe('First group',()=>{
test('rendering App component',()=>{
// App includes 'import { useAuthenticator } from '#aws-amplify/ui-react';'
render(<App/>)
screen.debug()
})
})
Error outputs here.
● Test suite failed to run
TypeError: window.URL.createObjectURL is not a function
> 1 | import { useAuthenticator } from '#aws-amplify/ui-react';
| ^
2 |
3 | const App = () => {
4 | const { user } = useAuthenticator((context) => [context.user]);
at define (node_modules/maplibre-gl/dist/maplibre-gl.js:25:43)
at node_modules/maplibre-gl/dist/maplibre-gl.js:35:1
at node_modules/maplibre-gl/dist/maplibre-gl.js:3:81
at Object.<anonymous> (node_modules/maplibre-gl/dist/maplibre-gl.js:6:2)
at Object.<anonymous> (node_modules/#aws-amplify/ui-react/dist/index.js:1:484)
at Object.<anonymous> (src/App.tsx:1:1)
Based on slideshowp2's answer, added setup and config file. But still hits the error. Both are located rootDir.
jest.setup.js
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
};
UPDATE
This PJ was created by CRA so it required to follow their rule. I finally resolved this by slideshowp2's answer and the correct location to put the pollyfilling code.
src/setupTests.ts
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
See troubleshooting#jest
As of v2.15.0 of #aws-amplify/ui-react which included the release of Geo components, users of the Jest testing framework may run into the following error when attempting to run tests:
window.URL.createObjectURL is not a function
Please follow the steps below to resolve this issue.
Navigate to or create a Jest setup file for your project.
Add the following code to polyfill the unrecognized function in your Jest setup file:
jest.setup.js:
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
jest.config.js:
module.exports = {
//...
setupFilesAfterEnv: ['./jest.setup.js'],
//...
}
This is a known problem when using the jsdom library (a dependency of Jest) with a package that uses an unrecognized function. See this issue.

how does webpack import from external url

I am using webpack to manage my react application. Now I want to import a dependency from this url:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=gNO2wKVBNupZfafi0bl0sW3dIKqAHn4l">
traditionally I just put above code on my index.html file. But now how can I let webpack to load this url? And how my react js use that dependency?
when I launch webpack-dev-server, I will get below error:
ERROR in Entry module not found: Error: Cannot resolve module 'http://api.map.baidu.com/api'
Then I use little loader to load the url. Below is the javascript code to use loader:
import $ from 'jquery'
import React from 'react';
import ReactDOM from 'react-dom';
import load from 'little-loader';
import './main.css';
import './component';
import Search from './search/search'
load('http://api.map.baidu.com/api?v=2.0&ak=gNO2wKVBNupZfafi0bl0sW3dIKqAHn4l', function(err){
console.log('err:', err);
});
// document.body.appendChild(component());
ReactDOM.render(<Search />, document.getElementById('search'));
but I still got below error when launch webpack:
ERROR in Entry module not found: Error: Cannot resolve module 'http://api.map.baidu.com/api' in /Users/yzzhao/dev/react-demo/webpack_demo
In the future you should be able to use dynamic requires via System.import.
Webpack 2 will support them natively.
System.import('<url>')
.then(function() {
console.log('Loaded!');
});
If you don't want to wait for it, you could use a script loading library.
Example:
Install:
npm install little-loader --save
Use:
import load from 'little-loader';
load('<url>', (err) => {
})
Or do it manually
function load(url) {
return new Promise((resolve, reject) => {
var script = document.createElement('script')
script.type = 'text/javascript';
script.async = true;
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
})
}
load('<url>')
.then(() => {
console.log('Loaded!');
})
.catch((err) => {
console.error('Something went wrong!', err);
})

Resources