vue2-leaflet-draw-toolbar: draw:created not firing when moving to production - vuejs2

I've been having trouble getting drawn polygon's geojson in production. When I run the app locally, draw:created fires and I can see the geojson in my requests. Here's the code:
const map = this.$refs.map.$refs.map;
map.mapObject.on("draw:created", (e) => {
this.searchPolygon = e.layer.toGeoJSON();
});
map.mapObject.on("draw:deleted", (e) => {
this.searchPolygon = {};
});
However, for some reason when running it in production, no geojson makes it into 'searchPolygon' after drawing a shape on the map. If i delete the shape I get "firing draw:deleted" in the console.
I'm running the same Docker image of my frontend locally and in production. I can see the mapObject in both environments and the layer is being created when I draw the shape, I've run out of ideas of where to look. Any ideas would be appreciated.
I've tried to change the refs, thinking maybe it's not finding the mapObject. But if I remove the refs, an error is thrown that "mapObject is not found". When i run the code like it is above, there are no errors thrown in console. Deleting the shape seems to fire draw:deleted since the codebase has a console.log that prints "firing draw:deleted".

Related

<video> tag. DOMException: The element has no supported sources, when not utilizing require()

I am trying to play a video when developing locally with VueJS 2.
My code is the following :
<video class="back_video" :src="`../videos/Space${videoIndex}.mp4`" id="background-video"></video>
...
data :
function() {
return {
videoIndex:1
}
}
...
const vid = document.getElementById("background-video");
vid.crossOrigin = 'anonymous';
let playPromise = vid.play();
if (playPromise !== undefined) {
playPromise.then(function() {
console.log("video playing");
}).catch(function(error) {
console.error(error);
});
}
This code is causing the exception given in title. Tried in several browsers, always the same.
If I change the src by :
:src="require(`../videos/Space${videoIndex}.mp4`)"
it works.
But in that case building time is very long as I have many different videos in my videos directory, because adding require() will force to copy all videos in the running directory at build phase (vue-cli serve), and this is really annoying. In other words I want to refer videos that are outside the build directory to avoid this (but also to avoid having videos in my git).
It is interesting to note that when I deploy server side, it works perfectly with my original code
:src="`../videos/Space${videoIndex}.mp4`"
Note also that if i replace my code with simply
src="../videos/Space1.mp4"
it works too. So the video itself, or its location, are not the source of the problem.
Any clue ?
You can host your videos on a CDN to have something faster and easier to debug/work with.
Otherwise, it will need to bundle it locally and may take some time.

WebRTC what is the correct way to removeStream and addStream again

My RTC session was started with text only. And video is added by user when needed (renegotiation)
navigator.getUserMedia({ video: true, audio: false }, function (myStream) {
localVideo[0].srcObject = myStream;
myConn.addStream(myStream);
}, function (error) {
console.log(error);
});
When user do not need the video session anymore, I remove using:
var tracks = localVideo[0].srcObject.getTracks();
tracks.forEach(function (t) {
t.stop();
});
myConn.removeStream(localVideo[0].srcObject);
localVideo[0].srcObject = null;
Everything is working fine, until I try to add the video again I noticed that the createOffer() request size is getting larger and larger.
Seems to me that WebRTC didn't forget about the previous stream, and is adding to the offer again and again. Or maybe my way of removing a video stream / track is wrong?
This is a known issue see this thread on the W3C list.
The best way to get around this is to use replaceTrack and is suggested in the thread.
Note: It is still possible to prevent the list of transceivers from growing
by *manually* recycling them using transceiver.sender.replaceTrack() and
transceiver.direction, but that still wastes resources on transceivers
currently not used, and implies you probably shouldn't use
transceiver.stop() in most cases.
Also see the "Unified Plan" Transition Guide

Uploading image [Cypress]

I'm trying to upload a jpeg image from local files to a webpage developed here in my job. The thing is, we need to click on the page to open the file explorer and then select the image (or drag and drop into the same spot that may be clicked).
Here is a picture from the web page
I don't know how could i do that, i was trying some code that i've seen in "https://medium.com/#chrisbautistaaa/adding-image-fixtures-in-cypress-a88787daac9c". But don't worked. I actually don't know how it works exactly, could anyone help me?
Here is my code
After #brendan's help, I was able to solve the problem by finding an input that was "hidden" under an element. However, before that I tried drag-n-drop, and cypress returned me an error (despite the successful upload). The context was, immediately after the upload, the element re-renders and cypress told me that:
.
Beside the success with input element, i was wondering how it would be possible to resolve this error, is it possible to do something internally to cypress to ignore or wait until the element re-renders back to normal?
Solutions suggested by cypress:
We're doing this using cypress-file-upload
Here's an example from our code:
cy.fixture(fileName).then(fileContent => {
cy.get(selectors.dropZoneInput).upload(
{ fileContent, fileName, mimeType: "application/pdf" },
{ subjectType: "drag-n-drop" }
);
});
For your purpose, I think this will work:
cy.fixture(imagePath).then(fileContent => {
cy.get(".upload-box").first().upload(
{ fileContent, fileName, mimeType: "image/jpeg" },
{ subjectType: "drag-n-drop" }
);
});

Image require() in nuxt with hot reload by HRM webpack

I use the dynamic source for vue-webpack images in nuxt :src="require('path/to/image' + dynamic.variable)" in my project navbar. If the users substitute their image through a form which refetches their information and deletes their previous image I get a webpack error module (img) not found (it does not find the new one): is there a way to solve this, like wait for webpack HRM to finish?
I tried setting up a setTimeout() of one second before user re-fetch and it works, but I don't like a random waiting, I'd use a promise or a sync dynamic, the point is webpack hot reload is not controlled by my functions.. I also tried with setting the dynamic path as a computed: but it doesn't fix.
My image tag:
<img v-if="this.$auth.user.image" class="userlogo m-2 rounded-circle" :src="require('#assets/images/users/' + this.$auth.user.image)" alt="usrimg">
My Useredit page methods:
...
methods: {
userEdit() {
//uploads the image
if (this.formImageFilename.name) {
let formImageData = new FormData()
formImageData.append('file', this.formImageFilename)
axios.post('/db/userimage', formImageData, { headers: { 'Content-Type': 'multipart/form-data' } })
// once it has uploaded the new image, it deletes the old one
.then(res=>{this.deleteOldImage()})
.catch(err=>{console.log(err)})
}else{
this.userUpdate() //if no new image has to be inserted, it proceeds to update the user information
}
},
deleteOldImage(){
if(this.$auth.user.image){axios.delete('/db/userimage', {data: {delimage: this.$auth.user.image}} )}
console.log(this.$auth.user.image + ' deleted')
this.userUpdate() // it has deleted the old image so it proceeds to update the user information
},
userUpdate(){
axios.put(
'/db/user', {
id: this.id,
name: this.formName,
surname: this.formSurname,
email: this.formEmail,
password: this.formPassword,
image: this.formImageFilename.name,
})
.then(() => { console.log('User updated'); this.userReload()}) // reloads the updated user information
.catch(err => {console.log(err)} )
},
userReload(){
console.log('User reloading..')
this.$auth.fetchUser()
.then(() => { console.log('User reloaded')})
.catch(err => {console.log(err)} )
},
}
...
the problem happens after "console.log('User reloading..')" and before "console.log('User reloaded');", it is not related to the file upload nor the server response. I broke a single function in many little ones just to check the function progression and its asynchronous dynamics but the only one that is not manageable is the webpack hot reload :/
I'd like the users to upload their images and see their logo in the Navbar appear updated after submitting the form.
First of all, as somebody told you in the comments, webpack hmr shouldn't be used for production.
In Nuxt, everything that you reference from the assets folder will be optimized and bundled into the project package. So the ideal use case for this folder is all assets that can be packaged and optimized, and most likely won't change like fonts, css, background images, icons, etc.
Then, require is called only once by webpack when it is either building the site for local development or building the site for generating a production package. The problem in your case is that you delete the original file while you're in development and webpack tries to read it and fails.
In the case of these images that the user uploads, I think you should use the static folder instead and instead of using require you'll have to change the :src with
:src="'/images/users/' + this.$auth.user.image"
Let me know if this helps.
Okay, I probably solved it.
HMR: you are of course right. Thank you for pointing out, I am sorry, I am a beginner and I try to understand stuff along the way.
Aldarund, thank you, your idea of not changing the path and cache it client side.. I am too noob to understand how I could implement it ( :) ) but it gave me a good hint: the solution was to keep the image name as the user id + the '.png' extension and to manage the image with jimp so that the image name, extension and file type are always the same, and with or without webpack compiling the new path, I always have the correct require().
Jair, thank you for the help, I didn't follow that road, but I will keep it as a second chance if my way creates errors. Just to be specific: the error comes when it does not find -and asks for the name of- the NEW image, not the OLD one, as I wrote in my question: it happens because the fetchUser() functions reloads the user information including the new image name.
Do you guys see any future problems in my methodology?
Really thank you for your answers. I am learning alone and it's great to receive support.

Disable error overlay in development mode

Is there a way to disable the error overlay when running a create-react-app in development mode?
This is the overlay I'm talking about:
I'm asking this because im using error boundaries (React 16 Error Boundaries) in my app to display error messages when components crashes, but the error overlay pops up and covers my messages.
An alternate solution is to add the following CSS style:
iframe
{
display: none;
}
This prevents the error from showing.
We don't provide an option to disable the error overlay in development.
Error boundaries do not take its place (they are meant for production use).
There is no harm having both the development error overlay and your error boundary; simply press Escape if you'd like to view your error boundary.
We feel the error overlay provides tremendous value over your typical error boundary (source code, click to open, etc).
It is also vital as we explore enabling hot component reloading as a default behavior for all users.
If you feel strongly about disabling the overlay, you'll need to eject from react-scripts and discontinue use of webpackHotDevClient. A less intrusive method may be removing the error event listener installed by the overlay off of window.
The error overlay can be disabled by using the stopReportingRuntimeErrors helper utility in the react-error-overlay package.
First, install the react-error-overlay package:
yarn add react-error-overlay
Then in index.js — right before mounting the root React component, import the utility and invoke it like this:
import { stopReportingRuntimeErrors } from "react-error-overlay";
if (process.env.NODE_ENV === "development") {
stopReportingRuntimeErrors(); // disables error overlays
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
Error overlays in create-react-app should now be disabled.
You can suppress React's error event handling by capturing the event first.
for example, by placing in public/index.html's <head>:
<script>
window.addEventListener('error', function(e){
// prevent React's listener from firing
e.stopImmediatePropagation();
// prevent the browser's console error message
e.preventDefault();
});
</script>
Since you probably still want React's error overlay for errors outside the error boundary, consider this option:
<script>
window.addEventListener('error', function(e){
const {error} = e;
if (!error.captured) {
error.captured = true;
e.stopImmediatePropagation();
e.preventDefault();
// Revisit this error after the error boundary element processed it
setTimeout(()=>{
// can be set by the error boundary error handler
if (!error.shouldIgnore) {
// but if it wasn't caught by a boundary, release it back to the wild
throw error;
}
})
}
});
</script>
assuming your error boundary does something like:
static getDerivedStateFromError(error) {
error['shouldIgnore'] = true;
return { error };
}
The result is a behaviour that follows try...catch line of reasoning.
To solve this issue, you could use CSS:
body > iframe {
display: none !important;
}
for some reason the overlay popped up for me only now while upgrading to Webpack 5.
In any case, you can now cancel the overlay by adding in your webpack.config.js:
module.exports = {
//...
devServer: {
client: {
overlay: false,
},
},
};
Or through the CLI: npx webpack serve --no-client-overlay
Taken from here: https://webpack.js.org/configuration/dev-server/#overlay
To avoid bundling in this large dev library in prod you can use a
dynamic import:
yarn add react-error-overlay
if (process.env.NODE_ENV === 'development') {
import('react-error-overlay').then(m => {
m.stopReportingRuntimeErrors();
});
}
In config/webpack.config.dev.js, comment out the following line in the entry array
require.resolve('react-dev-utils/webpackHotDevClient'),
And uncomment these two:
require.resolve('webpack-dev-server/client') + '?/',
require.resolve('webpack/hot/dev-server'),
I think this makes sense but sometimes when you are typing and have an error boundary then the overlay pops up with each character stroke and is annoying. I can remove the handler I suppose.
In the file webpack.config.js, comment the line:
// require.resolve('react-dev-utils/webpackHotDevClient'),
And uncomment:
require.resolve('webpack-dev-server/client') + '?/',
require.resolve('webpack/hot/dev-server'),
In the file webpackDevServer.config.js, comment:
// transportMode: 'ws',
// injectClient: false,
hide it with adblock
It is very useful to disable the errors temporarily so you don't have to comment/uncomment parts of your code that is not used at the moment, but it definitely will be after a few more changes.
The quickest solution is to just use adblock to pick the iframe with the errors.
It is trivial to toggle it with a single click to enable / disable adblock on the given page.
It is counter-intuitive to overlay the rendered page in development mode just to inform the user the newly imported objects or the recenlty created variables are not yet used.
I would say it is an arrow to the knee for beginners :)
If you are using the latest version with react-script >= 5.0.0, you just need to add an environment variable ESLINT_NO_DEV_ERRORS=true.
https://create-react-app.dev/docs/advanced-configuration
There is no option for it.
But, if you strongly wanted to disable modal window, just comment out this line
https://github.com/facebook/create-react-app/blob/26f701fd60cece427d0e6c5a0ae98a5c79993640/packages/react-dev-utils/webpackHotDevClient.js#L173
I had the same problem and I have been digging in the create-react-app source for a long time. I can't find any way to disable it, but you can remove the listeners it puts in place, which effectivly stops the error message. Open the developerconsole and select the html tag. There you can remove the event listeners on error and unhandlerejection which is put in place by unhandledError.js. You can also close the error message by clicking the x in the upper right corner of the screen, and then you should see your message.
Gathering answers here together, I managed to solve this issue for myself.
Here is the package I created for this.
The css fix has changed:
body > hmr-error-overlay {
display: none;
}
I'll also recommend adding this block on init so that you don't get silent errors:
window.addEventListener('error', function (e) {
console.error(e.message);
// prevent React's listener from firing
e.stopImmediatePropagation();
// prevent the browser's console error message
e.preventDefault();
});