Simple Peer on data stream throws process not defined error - reactjs

I am trying to open a data channel using simple peer. I send the signal using Firebase and am able to get the on connect function to fire.
const [thisPeer, setThisPeer] = useState();
const [connectionStatus, setConnectionStatus] = useState(false);
// in a function
var thisPeerT = new Peer({
initiator: false,
config: {
iceServers: iceServers,
},
});
// signaling code
thisPeerT.on("connect", function (data) {
console.log("onconnect");
console.log(data);
setConnectionStatus(true);
});
setThisPeer(thisPeerT);
In the on connect, I set a state hook that triggers a use effect where I create my on data.
useEffect(
function () {
console.log("here");
console.log(roomID);
console.log(thisPeer);
console.log(connectionStatus);
if (roomID && thisPeer && connectionStatus) {
console.log("here2");
thisPeer.on("data", function (data) {
console.log(data);
});
}
},
[roomID, thisPeer, connectionStatus]
);
However, I get the following error when I try to use thisPeer.on("data"...
here
XXYDCgqle4XvZDZ6gm6
Peer {_readableState: ReadableState, readable: true, _events: {…}, _eventsCount: 4, _maxListeners: undefined, …}
true
here2
Uncaught ReferenceError: process is not defined
at resume (_stream_readable.js:905:1)
at Peer.Readable.resume (_stream_readable.js:895:1)
at Peer.Readable.on (_stream_readable.js:813:1)
at ConnectionContext.js:142:1
at invokePassiveEffectCreate (react-dom.development.js:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
I have tried placing the on data at various places throughout my code, and regardless of the position, it seems this error occurs. If I call peer.send() on the other peer, it also gives a process is not defined error on the peer that received the data. Does anyone know how I can resolve the error or where I should open the data channel?

I got the same issue but I can do a workaround by using CDN script
<script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.11.1/simplepeer.min.js"></script>
And here is a code example of how to call it in React
var peer1 = new window.SimplePeer({ initiator: true })

Related

I am using React Native Expo And need to do live background location tracking

React Native Expo: Background Location has not been configured. To enable it, add location to UIBackgroundModes in Info.plistfile
I am using expo-location and trying to do background location tracking.
my app.json under IOS includes this
"infoPlist": { "UIBackgroundModes": [ "location", "fetch" ],
I am calling the startLocationUpdatesAsync function as such
` useEffect(() => {
var appLocation = undefined;
const startLocationTracking = async () => {
var opts = {
accuracy: Location.Accuracy.BestForNavigation,
distanceInterval: 1, //meters
};
appLocation = await Location.watchPositionAsync(opts, (location) => {
dispatch(setCurrentLocation(location.coords));
sendLocationToAPI(location);
});
const backgroundLocation = await Location.startLocationUpdatesAsync("background-location")
}`
I end up getting this error
Unhandled promise rejection: Error: Background Location has not been configured. To enable it, add locationtoUIBackgroundModes in Info.plist file.
I Do not know how to get rid of this, but I think I may have to expo eject and switch to cli. If anyone can help so I can avoid this it would be really helpful.

Error with URL in NextJS and I can't find the problem

I have an error that appear in both development and production mode, however, this error only crash the website in production.
I have this error returned:
unhandledRejection: TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1305:9)
at D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1410:19
at new Promise (<anonymous>)
at Function.fetch [as default] (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1407:9)
at fetchWithAgent (D:\FIV\nextjs-fiv-4\node_modules\next\dist\server\node-polyfill-fetch.js:38:39)
at _callee$ (D:\FIV\nextjs-fiv-4\node_modules\swell-js\dist\api.js:191:20)
at tryCatch (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:294:22)
at Generator.next (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:119:21)
at asyncGeneratorStep (D:\FIV\nextjs-fiv-4\node_modules\swell-js\node_modules\#babel\runtime\helpers\asyncToGenerator.js:3:24)
And I know that this is the element below causing this error, when I remove it, the error disappears. But I do not understand how to correct it, or what's wrong when checking the network tab. In the network tab I see that this is calling http://localhost:3000/null/api/cart instead of https://my-store.swell.store/api/cart which is weird because on other page this URL is called correctly and I use an .env file to set my environment variables.
//Render Stripe Card Element
var customCardElement = swell.payment.createElements({
card: {
elementId: '#card-element', // default: #card-element
options: {
style: {
base: {
fontWeight: 500,
fontSize: "16px"
},
},
},
onChange: event => {
//setDisabled(event.empty);
if(event.error){
//setError(event.error.message);
}
}
}
});
Client side NextJS variables are only available if prefixed with NEXT_PUBLIC_ because well... they're public

TypeError from screenfull library during jest test

I've added screenfull, a wrapper for the Fullscreen API (https://github.com/sindresorhus/screenfull.js) to a Redux-connected React component. The application uses Typescript elsewhere, but not in the components. Screenfull is used as follows in the component:
componentDidUnmount() {
screenfull.on('change', () => this.props.toggleFullscreen());
}
componentWillUnmount() {
screenfull.off('change', () => this.props.toggleFullscreen());
}
and I have a test as follows (there are more failing in the component test file, but I thought I'd share the first one)
it('mounts with initial state', () => {
const store = configureStore(reducer);
const container = mount(
<Provider store={store}>
<VideoBoundingBoxApp inIframe={false} />
</Provider>);
expect(container.find('VideoBoundingBoxApp')).toExist();
});
The application runs and works as expected, but when running yarn test, I get the following error:
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Uncaught [TypeError: _screenfull2.default.on is not a function]
at reportException (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
at invokeEventListeners (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:209:9)
at HTMLUnknownElementImpl._dispatch (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
at HTMLUnknownElement.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
at Object.invokeGuardedCallbackDev (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:944:16)
at invokeGuardedCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:993:29)
at commitRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7157:9)
at completeRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8065:36) TypeError: _screenfull2.default.on is not a function
at VideoBoundingBoxApp.componentDidMount (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/src/components/VideoBoundingBox/VideoBoundingBoxApp.jsx:122:28)
at commitLifeCycles (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:5347:26)
at commitAllLifeCycles (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7018:9)
at HTMLUnknownElement.callCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:906:14)
at invokeEventListeners (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
at HTMLUnknownElementImpl._dispatch (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
at HTMLUnknownElement.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
at Object.invokeGuardedCallbackDev (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:944:16)
at invokeGuardedCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:993:29)
at commitRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7157:9)
at completeRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8065:36)
at performWorkOnRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8015:11)
at performWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7933:9)
at performSyncWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7910:5)
at requestWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7810:7)
at scheduleWorkImpl (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7685:13)
at scheduleWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7645:12)
at scheduleRootUpdate (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8273:5)
at updateContainerAtExpirationTime (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8301:12)
at Object.updateContainer (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8328:14)
at Object.create (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9009:18)
at Object.<anonymous> (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/src/test/components/VideoBoundingBox/VideoBoundingBoxApp.test.jsx:42:49)
at Object.asyncFn (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/jasmine_async.js:82:37)
at resolve (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:52:12)
at new Promise (<anonymous>)
at mapper (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:39:19)
at promise.then (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:73:82)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(similar for screenfull.off...) I am not sure how to parse this. I don't think it's Typescript related. Would anyone have any idea?
I (well, mostly my boss) figured it out. Turns out, the screenfull code has a check for whether document contains methods such as requestFullscreen, otherwise it returns false. I fixed this by adding
// fullscreen library will cause an error in jest tests
// if it can't find fullscreen methods on document
[
'requestFullscreen',
'exitFullscreen',
].forEach(each => (document[each] = () => {})); // eslint-disable-line
to my setupTests.js
#Michel Schoemaker answer is correct, but I wanted to provide more context for those curious souls out there like myself. Thankfully, screenfull's source code is super short and easy to reason about.
Looking at the source, you'll see a self-invoking function right at the top which stores its return value in a variable called fn.
// This is what I'm talking about right here. See the end of this function
var fn = (function () {
var val;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// New WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Old WebKit
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
// This for loop essentially checks the current document object for the property/methods above.
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0; i < val.length; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
// If it doesn't find any of them, this whole function returns false
// and the fn variable is set to this returned value.
return false;
})();
Then further down in the you'll see for a simple conditional check on this fn variable.
// Sidenote, if you just remove the bang from the conditional, this package
// works in testing. But obviously we don't want to do that.
if (!fn) {
if (isCommonjs) {
module.exports = {isEnabled: false};
// If log out the value of screenfull after importing it
// in your test, this is what you'll see -> {isEnabled: false}
// Thus screenfull sets this object as the exported module and returns early.
} else {
window.screenfull = {isEnabled: false};
}
return;
}
So back to #Michel Schoemaker's answer; The reason that works is because we're basically monkey patching these properties/methods in the document object so Screenfull thinks we have a compatible environment. Once it think's we have a compatible environment, Jest can mock the library as usual.
I did things a little different than #Michel Schoemaker because I was only using screenfull in two methods of my application so I didn't need to set them up for my whole testing environment. Here' my approach:
thing.spec.js
import screenfull from 'screenfull';
jest.mock('screenfull');
//********* Fullscreen **********//
describe('Fullscreen', () => {
beforeEach(() => {
document.requestFullscreen = jest.fn();
document.exitFullscreen = jest.fn();
document.fullscreenElement = jest.fn();
document.fullscreenEnabled = jest.fn();
document.fullscreenchange = jest.fn();
document.fullscreenerror = jest.fn();
});
afterEach(() => {
jest.clearAllMocks();
});
test('test name', (done) => {
// Assemble
// Act
// Assert
expect(screenfull.toggle).toHaveBeenCalled();
done();
});
});
For one thing in the unit test you likely want to jest.mock this dependency.
And the _screenfull2.default.on is not a function error might be caused by mismatch between commonjs modules and es6 modules. How are you importing screenfull?

Redux-saga with Internet Explorer

I have a React app using redux-saga in IE 11
It seems to be breaking with the following error
Note that this app works perfectly fine in Chrome for versions of last 3 years and in Safari as well (aside for some display issues)
sagas.js
// functions are called bottom to top, this one is called at the end (also can be seen in stack trace below)
function* getGlobalData() {
console.log('Get global data called'); // this is executed
// something is failing from here on
const [
wardrobeResponse,
lastListingsResponse,
] = yield [
call(api_request, {url: 'store/wardrobes/'}),
call(api_request, {url: 'store/last_listings/'}),
]
yield put(actions.wardrobe.success(wardrobeResponse.json));
yield put(actions.lastListings.success(lastListingsResponse.json));
}
/**
* Watches for LOAD_SEARCH_RESULTS action and calls handler
*/
function* getGlobalDataWatcher() {
console.log('Get data - check if working');
console.log("global data watcher saga run")
yield take(Constants.LOAD_GLOBAL_DATA)
console.log('LOAD_GLOBAL_DATA received in saga')
const state = yield select()
if (state.getIn(['global', 'wardrobes']).isEmpty()) {
console.log('Empty global data, call api')
yield call(getGlobalData);
} else {
console.log('Global data already present, dont call API')
}
}
function* data() {
console.log('Get global results saga data called');
yield fork(getGlobalDataWatcher);
}
export default [
data
]
console error
uncaught at data
at loadMeDataWatcher
at loadMeData
TypeError: Object doesn't support this action
at api_request (http://localhost:3002/main.js:5905:3)
at runCallEffect (eval code:446:7)
at runEffect (eval code:370:5)
at next (eval code:259:9)
at currCb (eval code:329:7)
at runSelectEffect (eval code:651:7)
at runEffect (eval code:370:5)
at next (eval code:259:9)
at proc (eval code:214:3)
at resolveIterator (eval code:390:5)
You may install 'babel-polyfill' to your dependencies and add this line to your app.js.
import 'babel-polyfill';
See more

In-Context Checkout: Uncaught SecurityError: Blocked a frame with origin: checkout.js:4734 throws error

I'm implementing PayPal's In-Context Checkout and am using Advanced In-Context JavaScript settings (https://developer.paypal.com/docs/classic/express-checkout/in-context/javascript_advanced_settings)
My app is a React app. So I can't use PP API as they suggest it, that is just throw a code between <script> ... </script> tags somewhere in the page under their buttons. My React components have state and data that I need to send to server within PP function calls. So I placed PP code in componentDidMount method. And for some reason PP throws this error:
checkout.js:4734 Uncaught SecurityError: Blocked a frame with origin "http://example.com:3000" from accessing a frame with origin "https://www.sandbox.paypal.com". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
(anonymous function) # checkout.js:4734
checkout.js:4515 GET http://www.paypalobjects.com/api/oneTouch.html net::ERR_EMPTY_RESPONSE
Here is the code:
componentDidMount() {
window.paypalCheckoutReady = function() {
paypal.checkout.setup(config[NODE_ENV].ppMerchantID, {
locale: 'en_US',
environment: 'sandbox',
buttons: [
{
container: 'checkoutBtnContainer',
type: 'checkout',
color: 'gold',
size: 'medium',
shape: 'pill',
click: (ev)=>{
paypal.checkout.initXO();
$.post('/checkout', {
checkoutData: this.props.checkoutData,
})
.done(res => {
paypal.checkout.startFlow(res.link);
})
.fail(err => {
paypal.checkout.closeFlow();
});
}
}
],
});
};
},
I know about cross-origin policy. I don't understand why it is the case here. Why the code works fine if I throw it on the page between <script> ... </script> tags, but PP throws an error if I use it in my React component. What is the cause of that? Is it React fault or PayPal's?
UPD: No, below is not a solution for the problem. Occasionally Paypal's checkout.js script throws the error.
However, it solves this issue
Apparently,
1) there was no this:
window.paypalCheckoutReady = function() {
// wrong this is here
}
I changed to:
window.paypalCheckoutReady = () => {
// correct this is here now
}
I don't like .bind(this).
2) I removed <form /> tag and set plain <div> instead:
// before
<form id="checkoutBtnContainer" method="post" action="/checkout"></form>
// after
<div id="checkoutBtnContainer"></div>
I don't know why and how, but all works fine now.

Resources