I have react component:
const App = ()=> {
function ASD() {
alert("ASD");}}
I want in Chrome console type ASD(); and get the alert.
Just add it to the global window object.
function ASD() {
alert('ASD');
}
window.ASD = ASD;
const App = () => {};
console
ASD(); // or
window.ASD();
Presuming - your code might be looking like following, since the one OP has provided, is not a valid react-component -
const App = ()=> {
function ASD() {
alert("ASD");
}
window.ASD = ASD; // add this to read `ASD` from console by using "window.global"
return null; // this was at-least missing for the App to be a valid functional component
}
OP wants to call ASD from console(developer-console in Chrome). That could be done by attaching the function to the window global variable - like done in the above code.
Related
MY PROBLEM
I have a server which receives streaming data over UDP and rebroadcasts the data over websockets. In my front-end I have 2 different components which pick up the data and render the values. Whenever my server broadcast the object, key A is picked up by component 1. And key B should be picked up by component B.
For debugging purposes, the code below works smooth if I were to use a single component, but as soon as I use both only 1 is able to fetch and update data correctly while the other does nothing. What am I doing wrong?
MY SERVER (Just the important stuff)
# Dict to hold values
var data = {"score" : 0, "session" : 0,}
# handle different incoming UDP packets
client.on(PACKETS.session, handle_session);
client.on(PACKETS.score, handle_score);
#update data.session object with new values
function handle_session(data) {
data['session'] = data.session
websocket.broadcast(data);
}
#update data.score object with new values
function handle_score(data) {
data['score'] = data.score
websocket.broadcast(data);
}
# Broadcast data function gets called in handle functions.
websocket.broadcast = function broadcast(data) {
websocket.clients.forEach(function each(client) {
console.log(data);
client.send(data);
});
};
MY REACT APP
CONTEXT.JS - Create my socket
export const socket = new WebSocket("ws://localhost:8000")
export const SocketContext = React.createContext();
APP.JS - I wrap both my components in SocketContext
function App() {
return (
<div className="App">
<SocketContext.Provider value={socket}>
< Score />
< Session />
</SocketContext.Provider>
</div>
SCORE.JS - Component number 1 loads the socket from context.
function Score() {
const [score, setScore] = useState(0)
const websocket = useContext(SocketContext);
useEffect(() => {
websocket.onmessage = function(e) {
var packet = JSON.parse(e.data);
setScore(packet.score)
}
}, [websocket,]);
return (
<h6>{score}</>
);
}
export default Score;
SESSION.JS - Component number 2 loads the same socket from context.
function Session() {
const [session, setSession] = useState(0)
const websocket = useContext(SocketContext);
useEffect(() => {
websocket.onmessage = function(e) {
var packet = JSON.parse(e.data);
setSession(packet.session)
}
}, [websocket,]);
return (
<h6>{session}</>
);
}
export default Session;
So when running the frontend and adding console logging in useEffect for both components, Only one runs at the time. Then when reloading the app. Another one runs. They never run both at the same time.
Do you have any specific error messages in the console?
This bit on the server-side seems problematic:
data['score'] = {data.score}
It seems that should be:
data['score'] = data.score;
Edit*
Also another issue I see is variable scope overwriting:
You set:
var data = {"score" : 0, "session" : 0,}
But later both your functions use data in their local scope which is not good and would cause issues:
function handle_session(data) {
Should probably be:
function handle_session(d) {
Also this:
websocket.broadcast = function broadcast(data) {
Should probably be:
websocket.broadcast = function broadcast(d) {
These functions can share the same inner scope variable, d because they are siblings.
***EDIT, UPDATED ANSWER
The issue is with the use of websocket.onmessage. Since websocket is a single instance shared between components, once the listener is set on the onmessage property inside App.js, subsequent children components will be ignored when they try to set the same listener on the same property on the same websocket instance.
The key is to use addListener instead!
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/message_event
I created a simple working React <> Express <> Websocket App example of your situation, resolved by using addListener. I reproduced your exact problem.
Now all 3 component's useEffects will properly listen as you expected.
Open a terminal and run: npm run dev
https://codesandbox.io/p/sandbox/bitter-mountain-q3x118
Hope that helps!
I'm trying to use map function in my vue component. I have a file upload input that will accept multiple files. Since I'm working with electron, I can't pass directly the files to the backend of the app so I want to use the Array.prototype.map() function to get files path and proces them after passing the array using the ipcRenderer.send() function. Anyway I get always this error this.$refs.selectedImages.files.map is not a function how I can fix it?
Here is the actual code I'm trying
handleFiles() {
this.files = this.$refs.selectedImages.files.map( (file) => file.path ); //this will cause the error
}, //
processFiles() {
this.isLoading = true;
window.ipcRenderer.send('processFiles', this.files);
window.ipcRenderer.on('', (event, data) => {
console.log(ecent, data);
saveAs(data, 'processed.mfs')
});
}
UPDATE
To try solve the problem I'm looping the FilesList to extract the path of each file and then pass it using ipcRenderer. The problem is that I'm not able to get the message on the background.js and I'm not sure why.
this.$refs.selectedImages.files.forEach( (file) => {
this.files.push(file.path) // this will push into the array the path of each file
})
window.ipcRenderer.send('processFiles', this.files);
//background.js
import { ipcMain } from 'electron'
ipcMain.on('processFiles', (event, data) => {
console.log(event, data) // the message will not arrive
})
The FileList object is actually not an array, and has no .map method. But you can access the files like this:
const files = this.$refs.selectedImages.files;
for (var i = 0; i < files.length; i++) {
console.log(files[i]);
}
I changed the code in a module and now when I run 'npm run build' I get the above error, altough the code works just fine on my local host! Is there a work around to make it work?
value: function render() {
var _props2 = this.props,
onPlaceSelected = _props2.onPlaceSelected,
types = _props2.types,
componentRestrictions = _props2.componentRestrictions,
bounds = _props2.bounds,
rest = _objectWithoutProperties(_props2, ['onPlaceSelected', 'types', 'componentRestrictions', 'bounds']);
return _react2.default.createElement('input', _extends({
ref: 'input',
onChange: (e) => {
if (!e.target.value) {
this.props.haveri(null)
} else {
let a = e.target.value;
var options = {
types: ['(cities)'] //this should work !
};
The error specifies the line with 'onChange: (e) => {', it's a code that I added to manipulate the module.
Thanks in advance
The module code you shared looks like it's already transpiled, so the arrow function might be off there as well as the let inside.
Try changing both, the arrow function for a normal function declaration and the let for a var and see how it goes.
I've been developing an app in react.
Just a Simple app, it has a feature where I check toggle/toggle state for items inside a list.
At utils.js I have
export const partial = (fn, ...args) => fn.bind(null, ...args)
const _pipe = (f, g) => (...args) => g(f(...args))
export const pipe = (...fns) => fns.reduce(_pipe)
but the there is a problem in App.js, when using the utils:
const getToggledTodo = pipe(findById, toggleCompleted)
the helpers' imports seem fine:
import {pipe, partial} from './lib/utils'
import {addTodo, generateId, findById, toggleCompleted,
updateTodo, removeTodo, filterTodos} from './lib/todoHelpers'
Still , the app complains
Uncaught TypeError: Cannot read property 'find' of undefined
doing console I get:
f2: function () {
return g(f.apply(undefined, arguments));
}
I looked at:
at findById (todoHelpers.js:15)
at utils.js:10
at Object.executeOnChange (LinkedValueUtils.js:132)
and seems to me the undefined is coming from linkedValue file at last line:
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
Not sure how .apply and .call relate to each other here, and seems to me that I'm missing an argument somewhere.
The final objective is to update of state complete/not complete in the db, plus an message in the UI saying that in fact the item has been updated.
Fun fact: if I hard code some similar structured object in App.js and use it in memory to change state, the error does not show... o_O.
It only appears when trying to connect to a 'db', which is still of course a mock. Don't know if its related but I think is worth mentioning.
Using json-server to mock db objects.
So my question is: how to debug this error? Can someone help me understand a bit how apply and call relate to this error.
Any pointers in the right direction would be very helpful and much appreciated.
I've got a pretty odd issue if I ask myself.
Currently I've got a function in my view which is something like this:
<h3 ng-click="{{ vm.open(item.info) }}"> {{ item.title }} </h3>
and a function in my controller looking like this:
open = (url) => {
console.log(url);
}
This function works as intended it writes out the slug of the item from the view. But the issue comes when I try to add my API service or a simple $http.get() call. It seems to break the entire function because if I add this to the function:
open = (url) => {
console.log(url);
result.getOpportunity(url).then(result => {
res = result.data;
var modal = res.title;
console.log(modal);
});
}
Nothing gets printed out in the console. not even the first console.log() that worked so pretty just seconds ago.
Can anyone tell me what is going on? I don't get any error in either console or terminal but something do seem to be broken somewhere.
Worth mentioning is that I'm using an yeoman generator called Angular fullstack which uses Babel.
If I look into my gulp serve:ed .controller.js file that when I use the function that works. the single console.log line my file contains this:
this.open = function (url) {
console.log(url);
};
and when I use the longer function which doesn't work this is in the ouputted controller.js:
on the line where the function that works was this is now: _initialiseProps.call(this); and later on this function:
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.open = function (url) {
console.log(url);
_this2.result.getOpportunity(url).then(function (result) {
res = result.data;
var modal = res.title;
console.log(modal);
});
};
};
so Babel rewrites pretty much. but the most peculiar thing I noticed was that if I call _initialiseProps.call(this); explicit via the console I get returned undefined which do make some sense because the function _intiliaseProps() function does not contain a function called call()
but when I call _initialiseProps(this); from the console I get an error returned with this:
post.controller.js:29 Uncaught TypeError: Cannot set property '_checkURLforHTTP' of undefined(…)
Which is kinda funny or i dont know.. tearing my hair right now. Anyway, the _checkURLforHTTP function contains this in the code before babel had it's thing going:
_checkURLforHTTP = (img) => {
if (img.indexOf('http://') > -1 || img.indexOf('https://') > -1 ) {
return 'url("' + img + '")';
} else {
return 'url("http://HARDCODED-URL-HERE' + img + '")';
}
};
and the same function in the babel-processed file is the following:
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this._checkURLforHTTP = function (img) {
if (img.indexOf('http://') > -1 || img.indexOf('https://') > -1) {
return 'url("' + img + '")';
} else {
return 'url("https://HARDCODED-URL-HERE/' + img + '")';
}
};
};
Obviously it is something i'm not doing right, but i dont seem to understand what it is im doing wrong. I think I've managed to break it down into a click function in the view using $http.get();