React Learning Time [closed]

Let me tell in how much time you learn react js

Time required to learn react js. I want to learn react from which source I should learn it . If video tutorial of updated react available then share please

Pixelating a text element with css

I’m trying to create some intentionally terrible scaled-up text, anti-aliasing and all. I don’t want to use an image.

I tried blurring it, setting the font size to 1px and scaling it.. but that only jacked up the kerning. Any css gurus out there? All I can find on the web is how to FIX pixelated text.

API calls in beforeCreate

as in the beforecreate() lifecycle hook the data won’t be accessible what is the purpose to make API calls in it (I came accross it in many cases)

here an example:

  beforeCreate() {
    this.$myService.isEnabled().then(value => {
      this.isEnabled = value;
    }).finally(() => {
      this.$myService.getAll();
    });

the service

export function isEnabled() {
  return fetch(`url`, {
    method: 'GET',
  }).then(resp => {
    if (!resp) {
      throw new Error('blocking error');
    } else {
      return resp.text();
    }
  });
}

is it a good or bad practice ?

Action Buttons in Nested Tables Tabulator on table levels to add and delete rows

I have a tabulator like this

function show_containers(frm){

    var nestedData = [
        {container:1, item_code:'Black Marble', uom:'Square Meter', qty:325, batches:[
            {
            batch:'B123456', length:10, width:8, count:10, total_sqmt: 800, deduction:0.00, net_sqmt:800, 
                sheets: [
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800}
                ]
            },
            {
            batch:'B123456', length:10, width:8, count:10, total_sqmt: 800, deduction:0.00, net_sqmt:800, 
                sheets: [
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                    {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800}
                ]
            },
        ]},
        {container:1, item_code:'Black Marble', uom:'Square Meter', qty:325, batches:[
            {
         batch:'B123456', length:10, width:8, count:10, total_sqmt: 800, deduction:0.00, net_sqmt:800, 
             sheets: [
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800}
             ]
         },
         {
         batch:'B123456', length:10, width:8, count:10, total_sqmt: 800, deduction:0.00, net_sqmt:800, 
             sheets: [
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800},
                 {sheet:'S123456', length:10, width:8, total_sqmt: 800, deduction:0.00, net_sqmt:800}
             ]
         },
        ]}
    ]


    //define table
    var table = new Tabulator("#tabulator", {
        height:"100%",
        layout:"fitColumns",
        columnDefaults:{
        resizable:true,
        },
        data:nestedData,
        columns:[
            {title:"Container", field:"container"},
            {title:"Item Code", field:"item_code"},
            {title:"UOM", field:"uom"},
            {title:"Qty", field:"qty"},
        ],
        rowFormatter:function(row){
            //create and style holder elements
            var holderEl = document.createElement("div");
            var batchtableEl = document.createElement("div");

            holderEl.style.boxSizing = "border-box";
            holderEl.style.padding = "10px 10px 10px 30px";
            holderEl.style.borderTop = "1px solid #333";
            holderEl.style.borderBotom = "1px solid #333";
            

            batchtableEl.style.border = "1px solid #333";

            holderEl.appendChild(batchtableEl);

            row.getElement().appendChild(holderEl);

            var subTable = new Tabulator(batchtableEl, {
                height:"100%",
                layout:"fitColumns",
                data:row.getData().batches,
                columns:[
                {title:"Batch", field:"batch"},
                {title:"Length", field:"length"},
                {title:"Width", field:"width"},
                {title:"Count", field:"count"},
                {title:"Total SqMt", field:"total_sqmt"},
                {title:"Deduction", field:"deduction"},
                {title:"Net SqMt", field:"net_sqmt"},
                ],
                rowFormatter:function(row){
                    //create and style holder elements
                    var holderEl = document.createElement("div");
                    var sheettableEl = document.createElement("div");
        
                    holderEl.style.boxSizing = "border-box";
                    holderEl.style.padding = "10px 10px 10px 30px";
                    holderEl.style.borderTop = "1px solid #333";
                    holderEl.style.borderBotom = "1px solid #333";
                    
        
                    sheettableEl.style.border = "1px solid #333";
        
                    holderEl.appendChild(sheettableEl);
        
                    row.getElement().appendChild(holderEl);
        
                    var subTable = new Tabulator(sheettableEl, {
                        height:"100%",
                        layout:"fitColumns",
                        data:row.getData().sheets,
                        columns:[
                        {title:"Sheet", field:"batch"},
                        {title:"Length", field:"length"},
                        {title:"Width", field:"width"},
                        {title:"Total SqMt", field:"total_sqmt"},
                        {title:"Deduction", field:"deduction"},
                        {title:"Net SqMt", field:"net_sqmt"},
                        ]
                    })
                },
            })
        },
    });
}

I want to add action buttons on the level of Containers and Batches tables to add and delete rows

i want these buttons to add new rows and to delete selected rows and i want it to be on the table level

and the last table of sheets will have no action buttons.

i don’t want to use external action buttons.

getOrbit().disable() is not defined

So I am using this library https://dev.codemotionkids.com/libraries/diorama/docs/index.html

I wanted to use the function getOrbit().disable() to disable the camera rotation. However I face this error:

Uncaught TypeError: getOrbit(…).disable is not a function
at draw (sketch.js:166:14)
at _main.default.redraw (p5.js:70809:27)
at _draw (p5.js:63046:25)

If anybody, given that library understand where I am making the error, thank you. I also tried it in one of the examples provided but still had the same problem. If anybody knows how to fix it thank you

TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received type boolean (true)

When installing npm gives the following error:

enter image description here

Version node:

enter image description here

I tried to install with yarn, got the following result:

enter image description here

enter image description here

enter image description here

I can’t figure out what’s wrong, how can I fix it?

Install Node, Yarn. Deleted nvm, can’t do anything. Started reading windows environment variables but didn’t help.

Is there a way to use a named slot more than once in a Vue 3 component?

Assuming I have a component Section, which can have 1-N subsections and a styled footer, is there a way to do something like this?

<Section>
  // main content
  <template #subsection>
    // subsection 1
  </template>
  <template #subsection>
    // subsection 2
  </template>
  <template #footer>
    // footer
  </template>
</Section>

Typically I would model this as repeated child components inside of the parent but in this case the styling is easier to do in the parent on slots.

Is there a way to allow repeated use of a named slot?

New instance of class assigning different value to variable via constructor despite being passed a value

in a class called hero i have a key/value pair called watering can. when the first instance is created, the watering can value is initialized to 0 as expected.

when the data is used to create a new instance (via loading json from localstorage), the value pulled is still 0 – however when the class constructor is called the value becomes 10.

am i initializing these values incorrectly? i wasnt able to find code where they initialized variables like this inside of a constructor, however inside parameters for functions its common. does the constructor work differently?

watering can = 0 after loading json data
https://ibb.co/KKgZQ5x

creating new instance of hero class – watering can is now = 10
https://ibb.co/R32qtmB

hero class:

class Hero{
constructor(
    name, 
    gardenName, 
    appearance, 
    direction = 'down', 
    crypto = '1000', 
    location = _garden, 
    biome = 'plains', 
    locationName = gardenName, 
    popupControls = true, 
    stamina = 100, 
    maxStamina = 100, 
    sentiment = 'content', 
    wateringCan = 0, 
    maxWateringCan = 10) {
        this.name = name;
        this.direction = direction;
        this.crypto = crypto;
        this.gardenName = gardenName;
        this.location = location;
        this.biome = biome;
        this.locationName = locationName;
        this.appearance = appearance;
        this.popupControls = popupControls;
        this.stamina = stamina;
        this.maxStamina = maxStamina;
        this.sentiment = sentiment;
        this.wateringCan = wateringCan;
        this.maxWateringCan = maxWateringCan;
}

loading function:

    try{
    //retrieve hero object data from local storage data if available
    const json = JSON.parse(localStorage.getItem('valleyofblue'))

    //pull values from json to create new global hero object
    const { 
        name, 
        gardenName, 
        appearance, 
        direction, 
        crypto, 
        location, 
        biome, 
        locationName,
        popupControls,
        stamina,
        maxStamina,
        wateringCan,
        maxWateringCan
    } = json;

    console.log('WATERING CAN LOADED', wateringCan)
    debugger
    //create new hero object
    const newHero = new Hero(
        name, 
        gardenName, 
        appearance, 
        direction, 
        crypto, 
        location, 
        biome, 
        locationName,
        popupControls,
        stamina,
        maxStamina,
        wateringCan,
        maxWateringCan);

‘firebase:previous_websocket_failure’ error when trying to set data in Realtime Database

I am trying to set data in my Realtime Database using a Javascript front-end application.

I initialize everything at the start of my file as so:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-app.js';
import { getDatabase, ref, push, set } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-database.js';

const firebaseConfig = {
    //config info I have triple checked for accuracy
  };

const app = initializeApp(firebaseConfig);

const database = getDatabase(app);

Later on after validating data and creating variables I perform the following actions to set data in my database. I have created a parent node ‘orders’ in my database and made sure rules are open to accept all writes/reads.

const order = {
                customer: {
                    first_name: firstName,
                    last_name: lastName,
                    email: email,
                    phone: phone
                },
                order_date: orderDate,
                order_time: orderTime,
                order_method: orderMethod,
                order_address: orderAddress,
                has_plates: hasPlates,
                has_silverware: hasSilverware,
                has_napkins: hasNapkins,
                has_serving_utensils: hasServingUtensils,
                order_notes: orderNotes,
                order_total: orderTotal,
                order_items: {}
            }

            for (let i=0;i < localStorage.length; i++) {
                let item = localStorage.key(i);
                const itemPrice = item.slice(0,5);
                const itemName = item.slice(5,(item.indexOf('*')));
                const itemMods = item.slice(((item.indexOf('*'))+1) (item.indexOf('%')));
                const itemNotes = item.slice((item.indexOf('%')+1));
                const itemQuantity = JSON.parse(localStorage.getItem(item)).length;
                order.order_items[i] = {
                    item_quantity: itemQuantity,
                    item_name: itemName,
                    item_mods: itemMods,
                    item_notes: itemNotes,
                    item_price: itemPrice,
                };
            }

            console.log(order);

            //Push order data to Firebase

            const ordersRef = ref(database, 'orders');

            const newOrderRef = push(ordersRef);

            console.log('Set Up Complete');

            set(newOrderRef, order)
                .then(() => {
                    console.log('IT WORKED');
                    localStorage.clear();
                    // window.location.href = "../orderConfirmation-page/confirmed.html";
                })
                .catch((error) => {
                    console.error('Error saving order:', error);
                });
            
            console.log("Executed");

I expect to see data now in my Realtime Database but all I can get is a localStorage object(key: firebase:previous_websocket_failure, value: true) when this code block executes.

Any help or direction would be great, I know I need to set up better authentication rules and I’ve noticed my read/write rules getting turned back to false probably as a safety measure from google.

Fixed positioned element above css mask-image

I have scrollable content with mask-image. I need to use mask-image because I want to have transparency fadeout effect with every background color. Now I need to set child element with position fixed above the mask. Unfortunatelly I cannot because it seems that mask is still on top. Manipulating of z-index is not working

.faded {
  z-index: 1;
  background: red;
  width: 150px;
  height: 100px;
  overflow: auto;
  -webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 48px, black calc(100% - 48px), transparent 100%)
}

.fixed-header {
  position: fixed;
  top: 0;
  background: green;
  left: 0;
  z-index: 99999;
}
<div class="faded">
  <div class="fixed-header">
    Fixed Header
  </div>
  1) Item 1 - Test<br />
  2) Item 2 - Test<br />
  3) Item 3 - Test<br />
  4) Item 4 - Test<br />
  5) Item 5 - Test<br />

  6) Item 6 - Test<br />
  7) Item 7 - Test<br />
  8) Item 8 - Test<br />
  9) Item 9 - Test<br />
  10) Item 10 - Test<br />

  11) Item 11 - Test<br />
  12) Item 12 - Test<br />
  13) Item 13 - Test<br />
  14) Item 14 - Test<br />
  15) Item 15 - Test<br />
</div>

Vue2 – Plugin Install vs. Component lifecycle + main App, Mixins, Services, Vuex Actions – Organizing code that runs on initial startup

There are times when you need to add a bridge between an external API and your application. There’s two pieces to this – retrieving data from an API and writing that data to the store. And sending data to an API based on user action and updating the store on the client. Additionally, sometimes you need this code to run immediately on app startup. What’s a clean coding pattern to accomplish this in Vue?

This code (in my case) is global to the app and therefore it doesn’t make much sense to add it directly inside a UI component.

The simplest place to add this code would be the primary app mounted callback function.

new Vue({
  render: h => h(App),
}).$mount('#app');

// App.vue
mounted() {
  //run startup code here.
}

But as the app grows – it can get rather cluttered if the App.vue file is the “central” place for this type of functionality.

Choices and Tradeoffs

  • Mixins have collision issues making them not ideal especially if
    you’re adding several to the main parent component.
  • Plugins can be a good place for this sort of thing, but you can run into order of operations issues if the plugin expects something to exist and it doesn’t yet.
  • Templateless components can feel like a hack. You are adding a component into the template that doesn’t actually render anything beyond an empty <div>. Beyond that, they work.
  • Vuex Actions seem like the ideal place for this code, but the store lacks an internal triggering mechanism so the action still needs to be dispatched elsewhere, and if that’s App’s mounted callback we get back to the dumping ground concerns.
  • a Service/Utility (essentially abstracting the functions into another file and using ES6 module import/exports) is another way to abstract and organize code, but alone they are ignorant of the Vue instance and all the state and prototypes (other services, i18n, etc.). Passing the Vue instance as an argument also feels a bit hacky, and like there should be a more official “Vue” way.

A combination of a Vuex Action that’s triggered within a Plugin’s install callback might be the best choice here. Anyone have any better suggestions?

Implementing the observer pattern with nested elements

I’m trying to implement the observer pattern in JS without a controller, IE: the Model just re-renders the relevant views when its data changes.

My problem is that I need to pass a view to the model‘s registerObserver function as a reference, else I’ve no way to check that the observer hasn’t already been registered, here:

if (!this.observers.includes(observer)) 
  this.observers.push(observer)

If I can’t check the observers they’re continually added on every re-render, so I keep a reference to them in the nestedViews property. But I’m struggling with the problem that a parent view could also need to observe the model – so I add a reference to self. However if I re-render the parent view when the model changes I lose the references to the nested views, and the same problem occurs.

Relative to this approach I’m very new to webdev (this is just an exercise to improve my vanilla js), so I’m sure this must be an easy fix that I just can’t see?

Parent view:

class View {
   nestedViews = {};
   self = this;

   constructor(parentEl, model){
     this.model = model;
     this.parentEl = parentEl;
   }

   update() { this.render(); }

   render() {
     // method to render child classes
     this.onRender();
     // bind model
     this.bindModel();
    
     //... Logic to insert the item into the dom
   }
}

class NestedView extends View {
   bindModel() {
    Object.entries(this.nestedViews).forEach(([key, value]) =>
      this.model.registerObserver(value)
    );
   }
   onRender() {
    this.nestedViews['nestedView1'] = new NestedView1(
      parent,
      this.model
    );
    this.nestedViews['nestedView1'].render();
    
    this.nestedViews['nestedView2'] = new NestedView2(
      parent,
      this.model
    );
    this.nestedViews['nestedView2'].render();
   }}

Model:

class Model {
   observers = [];

   registerObserver(observer) {

   if (!this.observers.includes(observer)) this.observers.push(observer);
  }
  unregisterObserver(observer){
    this.observers = this.observers.filter((obs) => obs !== observer);
  }
  updateObservers() {
    this.observers.forEach((observer) => observer.update());
  }

  set() {
    // set attr
    this.updateObservers();
  }
}

Thanks

How can I trigger a click event when I click on a button that’s displayed outside of my dialog element?

I’m using the native HTML dialog element as a modal in my Vue 3 app and I’ve successfully displayed a button to the side/outside of the modal by using absolute positioning. However, due to the nature of dialog elements and how they’re placed in the top layer, I’m unable to trigger a click event (displayNextModal) when I click on the button outside of the dialog element. Adjusting the z-index of either element doesn’t have an effect as the dialog is always on the top layer by default. I’m wondering if there are any workarounds to this or if the only way to trigger this click event is if I put the button inside of the dialog element.

<template>
  <dialog class="modal-post" ref="postModalRef">
    <div>Modal screen</div>
  </dialog>
  <button class="next-modal-button" @click="displayNextModal">Next</button>
</template>
.modal-post {
  width: 500px;
  height: 600px;
}

.next-modal-button {
  position: absolute;
  width: 60px;
  height: 30px;
  color: black;
  top: 50%;
  right: 10px;
  z-index: 1000;
}

Jest fails to capture throw if async method of an object called within expect

I am seeing a behavior that I can not understand. The following test fails to capture the thrown error:

await expect(authService.register({ email, password })).rejects.toThrow();

While this one successfully captures the thrown error:

const register = authService.register;
await expect(register({ email, password })).rejects.toThrow();

I am aware this could be a bug, but this literally does not make sense to me, since expect function receives the exact same Promise in both cases, but still behaves differently. How is this behavior even possible?