Data reactivity in Vuejs – issue with loading data from and to multiselect

I am using vue-multiselect and I would like to store and later load selected values using localStorage. Storing data is quite OK for me, but I struggle with loading data back into the select component.

I was able to acomplish this task within one file, but in order to improve project readability, I have separated multiselect definitions into another file. Although it has improved the readability, but all other things get worse.

Please note, that there are more multiselects and more fields under formData.

  • Vue 3.x
  • vue-multiselect 3.0.0-beta.3

func.js

import formData from './formData.js'
import VueMultiselect from 'vue-multiselect'

export const TimeframeDropdown = {
  data() {
    return {
      selected: ["5m"],
      timeframes: ["5m", "15m"]
    };
  },
  watch: {
    selected(newVal) {
      formData.multiselect_input = newVal;
    }
  },
  render() {
    return (
      <VueMultiselect
        v-model={this.selected}
        options={this.timeframes}
        multiple={true}
      />
    );
  },
};
//There are more dropdowns in my code
...

formData.js

export default {
  multiselect_input: '',
  another_multiselect_input: '',
  yet_another_multiselect_input: ''
  //...
}
//There are more options in my code

page.vue

<TimeframeDropdown />
<AnotherDropdown />
<YetAnotherDropdown />
<button @click="store">store</button>
<button @click="load">load</button>

<script>
import * as t from './func.js'
import formData from './formData.js'

export default {
  components: {
    ...t,
  },
  data() {
    return {
      formData: formData
    }
  },
  methods: {
    store() {
      localStorage.setItem('test_key', JSON.stringify(this.formData.multiselect_input));
    },
    load() {
      const savedData = localStorage.getItem('test_key');
      this.formData = JSON.parse(savedData);
    },
   }
</script>

Need snippet or methods for thumbstick

I made a game in scratch and then ported it to html/js with turbowarp, but it isn’t supported on mobile. I need a way to send input into an iframe or into the page itself through js with a thumbstick. Thank you for your help if you reply, I honestly expect this to get downvoted tbh cuz idk if its possible as of right now but I would atleast like some information on the topic.

Haven’t tried anything. Haven’t found any docs online on stuff like this or anything.

Does JS have a single line element validator similar to ternary opperator?

C# allows you to do this for events

public event EventHandler ThresholdReached;//create event

ThresholdReached?.Invoke(this, e);//call event if not null

Notice the use of “?” which checks if the event is not null.

My question is does JavaScript have anything like this but for following functions like getElementById.
EX:

let varName = "some-id";
document.getElementById(varName)?.style.display = "none";

This would be the same as

let varName = "some-id";
let element = document.getElementById(varName);
if(element) {element.style.display = "none";}

I’m just seeing if there is a way to slim down my code while accounting for possible errors.

How do I push to a 2D array created with new Array() in Javascript?

I want to push an item at a given index of an empty 2D array, but for some reason, the item gets pushed into ALL the indices.

If I explicitly create the array, it works fine:

const arr = [[], [], []]
arr[1].push('a')
console.log(arr)
// [[], ['a'], []]

However, if I use new Array, it’s as though the reference to each index is shared and it gets added to ALL indices as stated earlier:

const arr = new Array(3).fill([])
arr[1].push('a')
console.log(arr)
// [['a'], ['a'], ['a']]

Why is this happening? If it’s unavoidable, what’s the best way to instantiate a 2D array in a clean manor, as with the second example AND be able to push elements to a single index?

AlpineJS Multiple Class Bindings, x-data, $persist + Flatpickr

I am attempting to disable a button using AlpineJS unless certain conditions are met. This is my button code:

<button
    class="bg-red p-4 rounded"
    :class="{'opacity-50 pointer-events-none': ((adults + children) === 0), 'opacity-50 pointer-events-none': charter === '' }"
>
Submit
</button>

This is my x-data, retrieving values from session storage with $persist

    x-data="{
        destination: $persist('').using(sessionStorage).as('_x_destination'),
        charter: $persist('').using(sessionStorage).as('_x_charterlength'),
        dateRange: $persist([]).using(sessionStorage).as('_x_range'),
        adults: $persist(0).using(sessionStorage).as('_x_adults'),
        children: $persist(0).using(sessionStorage).as('_x_children')
    }"

I have 3 different conditions I want to be met in order for the button to have pointe-events. The two above are partially working.

If adults + children is equal to zero, the button remains with no pointer events. If adults + children is equal to one or more, then the button still has no pointer events. This is good so far.

If I then update charter to not be null, the button now has pointer events and can be clicked.

However, if I the update charter to not be null first, prior to setting adults + children to be greater than zero, then the button somehow becomes active with pointer events before it should.

Not sure why the two conditions above aren’t working in conjunction with each other in either scenario.

Additionally, I have a third condition I would like to introduce into the button. That is x-datadateRange which is for use with Flatpickr

My Flatpickr code looks like this:

    <div x-data="{
        thePicker: null,
        init() {
            this.thePicker = flatpickr(this.$refs.picker, {
                mode: 'range',
                inline: false,
                dateFormat: 'M j',
                showMonths: 2,
                defaultDate: this.dateRange,
                onChange: (selectedDates) => {this.dateRange = [...selectedDates];}
            });
        },
    }"
    >
        <div
        class="flex items-center justify-center w-full overflow-hidden text-sm text-black bg-white border border-gray-400 rounded-lg"
        >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="ml-4 bi bi-calendar-event-fill" viewBox="0 0 16 16">
                <path d="M4 .5a.5.5 0 0 0-1 0V1H2a2 2 0 0 0-2 2v1h16V3a2 2 0 0 0-2-2h-1V.5a.5.5 0 0 0-1 0V1H4zM16 14V5H0v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2m-3.5-7h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5"/>
            </svg>
            <input type="text"
                x-ref="picker"
                placeholder="Add dates"
                class="px-4 py-2 text-sm placeholder-gray-600 border-0 bg-none focus:ring-0 "
            >
        </div>
    </div>

I am struggling to determine how to set the 3rd condition, even as the only condition, by setting 'opacity-50 pointer-events-none': dateRange === '' OR 'opacity-50 pointer-events-none': dateRange === null }

Nothing I’ve tried appears to recognize the Flatpickr as not being set.

How dynamically change the permissions of a text channel Discord.js?

I am writing a small bot that will allow uses in a voice channel to see a channel ment for people with no mics, then delete the channel after words.
I am able to see the people in a voice channel no problem but I am unable to create a channel that which has the PermissionsBitField.Flags.ViewChannel set to “deny” to “allow” after the channel is created.
I have members as an object and interaction from the a slash command.

async function restrictAccess(interaction, listeningMembers) {
    listeningMembers.forEach(member => {
        interaction.channel.permissionOverwrites.set([
            {
                id: member.user.id,
                allow: [PermissionsBitField.Flags.ViewChannel],
            }
        ]);
    });
}

I don’t know if I am writting it incorrectly or if I need to do something else after I check the users in the voice channel (I check the users in the voice channel whenever someone speaks, not the most optmized but whatever)

How can I center threejs object inside div?

I have this JS code, I am trying to center my object inside the div for my website. However I am unable to do it. I have tried posted solution but they did not work. I appreciate your help.

import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import {RGBELoader} from 'three/examples/jsm/loaders/RGBELoader.js';

// Scene 1 - Landing Page 

container = document.getElementById('canvas');
document.body.appendChild( container );


const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});

container.appendChild( renderer.domElement );

const div = document.getElementById('container');
div.appendChild(renderer.domElement);

renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( div.clientWidth, div.clientHeight,false);

const scene = new THREE.Scene();

const clock = new THREE.Clock();

const camera = new THREE.PerspectiveCamera(
    50,
    div.clientWidth / div.clientHeight,
    0.1,
    1000
);


const orbit = new OrbitControls(camera, renderer.domElement);

camera.position.x = 0
camera.position.y = 2
camera.position.z = 6
orbit.enabled = false
orbit.minDistance = 7;
orbit.maxDistance = 7;
orbit.update();

const gltfLoader = new GLTFLoader();

const rgbeLoader = new RGBELoader();

renderer.linearEncoding = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 10;

let obj1;
rgbeLoader.load('./assets/MR_INT-005_WhiteNeons_NAD.hdr', function(texture) {
    texture.mapping = THREE.EquirectangularReflectionMapping;
    scene.environment = texture;
    scene.background = null;


    gltfLoader.load( './assets/scene.gltf', function ( gltf ) {

        model = gltf.scene;
        scene.add(model);

        var textureLoader = new THREE.TextureLoader();
        textureLoader.load( "./textures/material0_baseColor.png", function ( map ) {
        model.material.map = map;
        model.material.map.encoding = THREE.sRGBEncoding;
        model.material.map.flipY = false;
        model.material.needsUpdate = true;
        });
    
        mixer = new THREE.AnimationMixer( model );
        
        gltf.animations.forEach( ( clip ) => {
          
            mixer.clipAction( clip ).play();
            obj1 = model;
        } );
    });

function animate(time) {
    requestAnimationFrame( animate );
    if (mixer) 
        delta = clock.getDelta();
        mixer.update(delta);
    renderer.render(scene, camera);
}

renderer.setAnimationLoop(animate);

window.addEventListener('resize', function() {
    camera.aspect = div.clientWidth / div.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( div.clientWidth, div.clientHeight,false);
});


});

Here is my html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css"> 
</head>
<body>
    <div id="container">
        <div id="canvas"></div>
    </div>
    <div id="container2">
        <h1>
            <span class="box"></span><span class="text"></span><span class="cursor">_</span>
        </h1>
    </div>

    <script src="./js/scripts.js" type="module"></script>
    <script src="./js/app.js" type="module"></script>
    <!--
        npm install @parcel/config-default -d
        
        "staticFiles": {
    "staticOutPath": "static"
    }
    -->
</body>
<script src="./js/scripts.js" type="module"></script>
<script src="./js/app.js" type="module"></script>
</html>

and the CSS file.

@import url('https://fonts.cdnfonts.com/css/modern-typewriter');
html {
  background-color: black;
  scroll-behavior: smooth;
  }
  
body {
    margin: 0;
    padding: 0;
    overflow-x: hidden;
  }

#container{
  background-color: blue;
  float: right;
  width: 500;
  height: 500;
}

h1 {
  position: relative;
  font-size: 2vw;
  font-weight: bold;
  padding-top: 20vw;
  padding-left: 5vw;
  overflow: hidden;
  color: aliceblue;
}

h1 .text {
  font-family: 'MODERN TYPEWRITER', sans-serif;
  font-weight: normal;
}

#container2{
  float: left;
  width: 50%;
}

Here is how I need it to be.

enter image description here

I have tried fixing the camera positions and CSS script but it does not work.

Securely use Firebase JS SDK with React Native Expo

Currently I’m building an app using React Native, Expo and Firebase I was wondering from anyone who has worked with the Firebase JS SDK and React Native via Expo what approach they took to securely communicate with and initialize Firebase.

For development I’m using environment variables to store API keys and other information about my Firebase project and I’m doing everything such as user auth, firestore actions like get and create docs etc. client side. But i know that everything client side isn’t considered secure and id like to be releasing the app / pushing it to production soon and I’m worried about security issues because there will be sensitive keys used for things like stripe. All in all i wanted to get an idea for how to do it with firebase so i can adapt to other sensitive items. I’ve used Django in the past and have read that using an api server is much more secure but I’ve also heard using serverless solutions like AWS lambda is also a good approach. Curious as to what approach others have taken when faced with this problem.

Implement tabs with htmx

I want to implement simple tab functionality with htmx for a Django template.
I know of the django_htmx package, but I chose to use htmx directly and I’m now having trouble implementing the tab functionality.

I tried using the example from the htmx website using JavaScript but I’m having trouble, all the prospective tabs are divs on the same page.

What are async Functions in JavaScript or Typescript?

what is the difference if a normal method or async method is called on an object ?

(1) myObject.handleUpdate()   // conventional method
(2) myObject.handleUpdate()   // handleUpdate is declared async

I know that async methods return always promise. But apart from that. Does async method run in a separate thread ? And what does it mean if an async method is called in a test framework. You need to wait for it ? In contrast a normal method (1) is called in the same thread you can call it without any hooks in a test framework

How do I delete an element from a database using angular js

I am currently practicing angular and starting with it, I’m also doing a MEAN stack application, and I’m trying to make a delete function in order to delete an element from the database, but it is not working, I keep getting this error:

enter image description here

I also have set "noPropertyAccessFromIndexSignature": false, since I’ve read that my current version of angular needs that option disabled in order to work with my code.

I’m trying to delete an element from my database, the reading of the elements works but I cannot delete them. This is my code:

export class ListarProductoComponent implements OnInit {

  listProductos: Producto[] =[];
  constructor(private _productoService: ProductoService,
    private toastR: ToastrService){}

  ngOnInit(): void {
    this.obtenerProductos();
    //throw new Error('Method not implemented.');
  }

  obtenerProductos(){
    this._productoService.getProductos().subscribe(data=>{
      //console.log(data);
    this.listProductos = data;
    }, error=>{
      console.log(error)
    })
  }


  eliminarProducto(id: any) {
      this._productoService['eliminarProducto'](id).subscribe((res: any) => {
      console.log("product deleted")
      this.obtenerProductos();
    }, (error: any) => {
      console.log(error);
    });
  }

}

which I’m calling from my html file:

<i (click)="eliminarProducto(producto._id)" class="fa-solid fa-trash text-danger"></i>
So I would like to know what solutions could I use, thank you.

Accessing a file path from an HTML input in Tauri

I have an app that I’m converting from Electron to Tauri. It’s pretty plain, just an HTML file with some client side JS in it. One of the things that it does is when you click a button, it opens a file dialog, and it saves the path of that file.

In Electron, it exposes the path, but Tauri doesn’t seem to. Any tips on how I can get that file path in the JS?

My HTML:

<input type="file" accept=".pdf" id="file" />

My JS:

document.getElementById("file").addEventListener("change", () => {
    pathUrl = document.getElementById("file").files[0].path;
    savePath();
});

Again, this works just fine in Electron, but I’m not sure how to Tauri-ify this.

I added the dialog thing to the allowlist:

"dialog": {
  "open": true
}

But I’m not sure if I’m on the right track!

Numbro v1 format for round numbers

I’m not able to find the exact format to round numbers (no digits after the decimal) in Numbro with the old format (v1).
Found a Github issue that looks like it’s the same question, but haven’t been able to find any other resource.
Using the try me from Numbro, I would want 12345.67 to be formatted as 12346 (rounding to 0 digits after the decimal). 0.0, 0., 0[.] and similar variants don’t work

Live update frontend

How can I update a webpage live, without the user refreshing the page or doing any thing?

Example: User is awaiting a new product to be revealed, until then we show a “the new product is commning soon” image. When we are ready to show the product image, everybody will get to see it at the same time.

I imagine that I must use fetch-api to replace content (image url). But how do I do that in a smart way? Will fetch need to be run every second, and wont that use many resources. Thanks so much!