VueJS2: How to update objects in an array and pass back to parent?

I have a parent component that is passing down some API data to a child component in order to pre-populate some input fields. When the user changes some of this data on the child component, that child component emits the data back to the parent where we will process it for server submission on user form submit.

To handle the updates for processing, I am sending the child data back as an object which the parent stores in an array (array of objects). This array is what I am sending to the server for processing.

I am struggling with how to update object properties in an array of objects.

Codesandbox: https://codesandbox.io/s/romantic-mestorf-yc0i1h?file=/src/components/Parent.vue

Let me explain in detail. I have 3 components:

<App>
    <Parent>
        <Child />
    </Parent>
</App>

App.vue:

    <template>
  <div id="app">
    <form @submit.prevent="submitForm()">
      <Parent
        :localShortNames="formValues.localShortNames"
        @save-form-data="saveFormData"
      />
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
import Parent from "./components/Parent.vue";
import data from "./assets/data.json"; // <--- will be an actual API request
export default {
  components: {
    Parent,
  },
  data() {
    return {
      formValues: {
        localShortNames: data,
      },
    };
  },
  methods: {
    saveFormData(x) {
      // TO DO
    },
    submitForm() {
      // TO DO: save data to server
    },
  },
};
</script>

Parent.vue:

<template>
  <div>
    <h5>List of Data</h5>
    <Child
      v-for="item in localShortNames"
      :key="item.localSnameID"
      :localShortName="item"
      @save-form-data="saveFormData"
    />
  </div>
</template>

<script>
import Child from "./Child.vue";
export default {
  props: {
    localShortNames: {
      type: Array,
    },
  },
  components: {
    Child,
  },
  data() {
    return {
      newLocalShortNamesArr: this.localShortNames,
    };
  },
  methods: {
    saveFormData(x) {
      let elementId = (el) => el.localSnameID === x.localSnameID;

      const newArr = this.newLocalShortNamesArr.map((obj) => {
        if (elementId) {
          // I need to update the existing object in newLocalShortNamesArr with updated user submitted properties
          // ...
        } else {
          // item does not exist, lets push it to newLocalShortNamesArr
          // TO DO LATER: create "add new data" button for adding new objects to array
    },
  },
},
},
}
</script>

Child.vue:

<template>
  <div>
    <label for="name-input">Name:</label>
    <input
      type="text"
      id="name-input"
      v-model="formValues.name"
      @input="$emit('save-form-data', formValues)"
    />

    <label for="dialect-input">Dialect:</label>
    <input
      type="text"
      id="dialect-input"
      v-model="formValues.iso6393Char3Code"
      @input="$emit('save-form-data', formValues)"
    />
  </div>
</template>

<script>
export default {
  props: {
    localShortName: {
      type: Object,
    },
  },
  data() {
    return {
      formValues: {
        localSnameID: this.localShortName
          ? this.localShortName.localSnameID
          : null,
        name: this.localShortName ? this.localShortName.name : null,
        iso6393Char3Code: this.localShortName
          ? this.localShortName.iso6393Char3Code
          : null,
      },
    };
  },
};
</script>

Question: How to handle the update of objects in an array and “overwrite” those properties (name, and iso6393Char3Code) if the same id exists in the original array?

In the parent.vue, I was thinking of doing something like this, but I don’t know:

    saveFormData(x) {
      // console.log(x);
      let elementId = (el) => el.localSnameID === x.localSnameID;

      const newArr = this.newLocalShortNamesArr.map((obj) => {
        if (elementId) {
          // I need to update the existing object in newLocalShortNamesArr with updated user submitted properties
          // ...
        } else {
          // item does not exist, lets push it to newLocalShortNamesArr
          // ...
        }
      });

Would Object.assign be better here vs map()? All I am trying to do is provide an array to the API called localShortNames that contains all the objects whether they have been updated or not. Hope this makes sense!

I have a codesandbox here with the above code: https://codesandbox.io/s/romantic-mestorf-yc0i1h?file=/src/components/Parent.vue

Syntax Error on TypeScript file when using TypeORM with JavaScript file

I’m getting a SyntaxError when running a TypeScript-compiled JS file [via TypeORM].

I have the following files:

// ./src/entity/Bird.ts

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Bird {
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    kingdom: string;
    
    @Column({length: 300})
    phylum: string;
    
    @Column()
    class: String;
    
    @Column({type: 'simple-array'})
    colors: string[];
    
    @Column({default: false})
    isActive: boolean;
    
    @Column({type: 'bigint', width: 100, default: Date.now()})
    timestamp_u: number;
}
// ./init.ts

import 'reflect-metadata';
import { createConnection } from 'typeorm';

async function start() {
    // initialize database
    let connection = await createConnection();

    // close connection
    await connection.close();
}

start().catch(console.error);
// ./ormconfig.json
{
   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "root",
   "password": "my~password",
   "database": "sandbox",
   "synchronize": true,
   "logging": false,
   "entities": [
      "dist/src/entity/**/*.js",
      "src/entity/**/*.ts"
   ]
}
// ./tsconfig.json
{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./dist",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "exclude": ["node_modules", "dist", "out"]
}

In package.json, type is set to commonjs [for ts-node to work properly];

I’m compiling TypeScript to JavaScript:

npx tsc

Then I’m running the JavaScript via Node:

node ./dist/init.js

When I do this, I get the following error:

Bird.ts:1
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^

SyntaxError: Cannot use import statement outside a module

The problem goes away when I change my ormconfig.json to this:

...
"entities": [
      "dist/src/entity/**/*.js"
   ]
...

Note: I’ve removed the entities directory for TypeScript files.

However, I need to re-include that directory when I use ts-node.

My questions are:

  1. Why is Node [via TypeORM I surmise] giving me an error regarding a .ts file when I’m running a .js file?
  2. Is there some configuration setting I can make to have both directories in place and not get the error?

How to convert an array of objects to a nested object [duplicate]

I get an array of nested objects from my rest api call.

[
{Title: "Category1", SubCategory: "subcategory1", SubSubCategory: "subsubcategory1", SubSubSubCategory:"subsubsubcategory1"},

{Title: "Category1", SubCategory: "subcategory1", SubSubCategory: "subsubcategory1", SubSubSubCategory:"subsubsubcategory2"},

{Title: "Category1", SubCategory: "subcategory2", SubSubCategory: "subsubcategory1", SubSubSubCategory:"subsubsubcategory1"},

{Title: "Category2", SubCategory: "subcategory1", SubSubCategory: "subsubcategory1", SubSubSubCategory:"subsubsubcategory1"}

{Title: "Category2", SubCategory: "subcategory1", SubSubCategory: "subsubcategory2", SubSubSubCategory:"subsubsubcategory1"}

]

which i need to format into an object like:

{
    name: "Category1",
    Subcategory: [
                   {
                     name: "subcategory1",
                     SubSubCategory: [
                                       {
                                          name: "subsubcategory1",
                                          SubSubSubCategory: [
                                                                  {name:"subsubsubcategory1"},
                                                                  {name:"subsubsubcategory2"}
                                                             ]
                                       }
                                      ]
                    },
                    {   

                     name: "subcategory2",
                     SubSubCategory: [
                                       {
                                          name: "subsubcategory1",
                                          SubSubSubCategory: [
                                                                  {name:"subsubsubcategory1"},
                                                                
                                                             ]
                                       }
                                      ]
                    }
                  ]
and so on...

}

I have tried this

const result = res.reduce((object, item) => {
    object[item.Title] = object[item.Title] || {}; 
    object[item.Title][item.SubCategory] = object[item.Title][item.SubCategory] || {};
    object[item.Title][item.SubCategory][item.SubSubCategory] = object[item.Title][item.SubCategory][item.SubSubCategory] || {};
    object[item.Title][item.SubCategory][item.SubSubCategory][item.SubSubSubCategory]; 
    return object;
  }, {});

But this does not fully according to my needs. It creates object keys as Category1, SubCategory1 like that.

I am new to js and having some issues in this area. Any help would be appreciated.

Does JQuery need some kind of reload when adding elements to the HTML? [duplicate]

I am having a weird issue.

I have a .js that is selecting by class some elements, like this:

$(function () {
    $(".myclass1, .myclass2").hover(function (event) {
        //Some styling code here
    })
})

When the document loads, everything works allright.
But when pushing a button, I need to change the appearance of the page, and then, some of the myclass1 and myclass2 elements are removed and some new are added (with those same classes).

But the hover function, which changes the color of those elements, only works with the ones that existed when the document was loaded at the beginning, and it does not interact or react with the new ones.

Is this an expected behavior from JQuery? I haven’t found anything regarding this so far.

how to make space between looped cards. i use ajax, jquery and bootstrap

enter image description here

there is no space between the cards. how to add a little bit of space between them?

.done((todos) => {
        todos.forEach(el => {
            console.log(el)
            $("#todo-list").append(`
             <div class="card col-6 col-sm-4" id="todo-${el.id}" style="width: 18rem; flex-wrap: wrap;">
                    <div class="card-body">
                        <h4 class="todo-title">${el.title}</h4>
                        <h6>${el.description}</h6>
                        <p>Due Date: ${el.due_date}</p>
                        <input type="checkbox" id="checkbox" onclick="updateStatus(${el.id})"> Status</input>
                        <a type="button" class="mw-100 btn-close col position-absolute top-0 end-0" aria-label="Close" id="btn-delete-todo" onclick="deleteTodo(${el.id})"></a>
                        </div>
                </div>
            `)
        })

How to access the value of a dynamic key in object Javascript

I have an object of object which consists of dynamic data, the ‘keys’ in the object are also dynamic. I want to access the fruit string in the following object.

let defaultKey = '0x';
let currentFruit = '';
    let obj = {
            id: 6595258,
            time: '21-09-30T10:21:40.000Z',
            data: {
                '0x': {
                    15: {
                        0: 'Apple',
                        15: 'Mango'
                    },
                },
              '3x': {
                    0: {
                        0: 'Orange',
                        15: 'Banana'
                    },
                    30: {
                        0: 'Strawberry',
                        15: 'Avocado'
                    },
                },
            },
        };
        

I have tried with Object.keys method but it doesn’t work. I just want to set ‘Apple’ to the currentFruit variable.

I just want to do something similar to

const key = '0x';
let obj = {
        id: 6595258,
        time: '21-09-30T10:21:40.000Z',
        data: {
            '0x': {
                15: {
                    0: 'Apple',
                    15: 'Mango'
                },
            },
          '3x': {
                0: {
                    0: 'Orange',
                    15: 'Banana'
                },
                30: {
                    0: 'Strawberry',
                    15: 'Avocado'
                },
            },
        },
    };

var currentKey = Object.keys(obj.data)[0];
if(key === currentKey) {
  //I want to set the fruit name into the currentFruit variable
}

How to remove css selector using javascript or jquery

I want to delete only this selector using javascript or jquery

#review .review-grid .card:hover {
    border: solid rgb(255, 59, 59);
}

the name (review) could change depending on the widget, but I can capture the widget by this code

  $(frame).contents().find('#' + widgetId).each(function (i, p) {
      console.log(p);
      return false;
  });

and the console return this HTML:

<div class="gpr-tablet gpr-mobile gp-selected" id="review" data-highlightable="1" data-section="true" data-column="true" data-parent-id="section_review_column_0" data-widget-label="ReviewGridWidget" style="min-height:20px;;"><div class="review-grid"><div class="container-fluid"><div class="row no-gutters"><div class="col-lg-4 col-md-4 col-sm-12 col-12 d-flex"><div class="card flex-fill"><div class="card-body text-center"><img data-src="https://lh3.googleusercontent.com/a/AATXAJwiE2s4pB4pHcvprxSfI_0YuumgeHnQJXcyXASN=s120-c-c0x00000000-cc-rp-mo-br100" class=" lazyloaded" src="https://lh3.googleusercontent.com/a/AATXAJwiE2s4pB4pHcvprxSfI_0YuumgeHnQJXcyXASN=s120-c-c0x00000000-cc-rp-mo-br100"><h6 class="card-title">杉本悦子</h6><p class="card-text"></p><p class="ratings"><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i></p></div></div></div><div class="col-lg-4 col-md-4 col-sm-12 col-12 d-flex"><div class="card flex-fill"><div class="card-body text-center"><img data-src="https://lh3.googleusercontent.com/a/AATXAJwYPYluN7eQhUol78374flZWzrglN18TVjxXOso=s120-c-c0x00000000-cc-rp-mo-br100" class=" lazyloaded" src="https://lh3.googleusercontent.com/a/AATXAJwYPYluN7eQhUol78374flZWzrglN18TVjxXOso=s120-c-c0x00000000-cc-rp-mo-br100"><h6 class="card-title">はっとりかずよ</h6><p class="card-text"><i class="fas fa-quote-left"></i><span>いつも髪の仕上がりに満足しています。

</span><i class="fas fa-quote-right"></i></p><p class="ratings"><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i></p></div></div></div><div class="col-lg-4 col-md-4 col-sm-12 col-12 d-flex"><div class="card flex-fill"><div class="card-body text-center"><img data-src="https://lh3.googleusercontent.com/a/AATXAJzL24zP3ML-0fOAKwrSXmp8gJfpip1dkGTqi9kU=s120-c-c0x00000000-cc-rp-mo-br100" class=" lazyloaded" src="https://lh3.googleusercontent.com/a/AATXAJzL24zP3ML-0fOAKwrSXmp8gJfpip1dkGTqi9kU=s120-c-c0x00000000-cc-rp-mo-br100"><h6 class="card-title">稲垣夢香</h6><p class="card-text"><i class="fas fa-quote-left"></i><span>カラーの色が、可愛いかったです。

</span><i class="fas fa-quote-right"></i></p><p class="ratings"><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="fas fa-star va-middle"></i><i class="far fa-star va-middle"></i></p></div></div></div></div></div></div></div>

the selector is located on the class

<div class="card flex-fill">

how can I delete the entire “border” selector? from that .card:hover

TypeError: Cannot read properties of undefined (reading ‘map’) even though useState() is initialized with array

I’ve got “TypeError: Cannot read properties of undefined (reading ‘map’)”, even though useState() is initialized with array. The error occurs only in one component. Other components, which, I think, are also using useState and useEffect the same way, don’t resolve with this error. my code ;)

I will be glad if anyone could point me in the right direction.

Auto population data not fetch when a new row is added dynamically to append table

                    <td><select name="productName[]" id="productName_1" class="form-control total">

    <option value="">Select Product</option>
</select>

                    </td>

                    <td><input type="number" placeholder="Enter Qty" min="1" value="" name="quantity[]" id="quantity_1" class="form-control quantity" autocomplete="off"></td>



                    <td><select name="price[]" id="price_1" value="" class="form-control total"></td>





                    <td><input type="number" name="total[]" id="total_1" class="form-control total" readonly="readonly" autocomplete="off"></td>
                </tr>   
                </form> 

                <tbody id="tbody"></tbody>

            </table>
        </div>
    </div>


    <div class="row">
        <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
            <button class="btn btn-danger delete" id="removeRows" type="button">- Delete</button>
            &nbsp;&nbsp;
            <button class="btn btn-success" id="addRows" type="button">+ Add Rows</button>

        </div>
    </div>
    <div class="row">   
        <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8">
            <h4>Items Description(If any): </h4>
            <div class="form-group">
                <textarea class="form-control txt" rows="5" name="notes" id="notes" placeholder="Items Description"></textarea>
            </div>
            <br>
            <div class="form-group">
                <input type="hidden" value="<?php echo $_SESSION['userid']; ?>" class="form-control" name="userId">
                <input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm"> 

                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <a href="21.php"><button class="btn btn-danger delete" type="button">Reset</button></a>                 
            </div>

        </div>
        <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <span class="form-inline">
                <div class="form-group">
                    <label>Subtotal: &nbsp;</label>
                    <div class="input-group">
                        <div class="input-group-addon currency">₹</div>
                        <input value="" type="number" class="form-control" readonly="readonly" name="subTotal" id="subTotal" placeholder="Subtotal">
                    </div>
                </div>
                <div class="form-group">
                    <label>Tax Rate: &nbsp;</label>
                    <div class="input-group">
                        <input value="18" type="number" class="form-control" readonly="readonly" name="taxRate" id="taxRate" placeholder="Tax Rate">
                        <div class="input-group-addon">%</div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Tax Amount: &nbsp;</label>
                    <div class="input-group">
                        <div class="input-group-addon currency">₹</div>
                        <input value="" type="number" class="form-control" readonly="readonly" name="taxAmount" id="taxAmount" placeholder="Tax Amount">
                    </div>
                </div>                          
                <div class="form-group">
                    <label>Total: &nbsp;</label>
                    <div class="input-group">
                        <div class="input-group-addon currency">₹</div>
                        <input value="" type="number" class="form-control" readonly="readonly" name="totalAftertax" id="totalAftertax" placeholder="Total">
                    </div>
                </div>
                <div class="form-group">
                    <label>Discount/Paid: &nbsp;</label>
                    <div class="input-group">
                        <div class="input-group-addon currency">₹</div>
                        <input value="" type="number" class="form-control" name="amountPaid" id="amountPaid" placeholder="Amount Paid">
                    </div>
                </div>
                <div class="form-group">
                    <label>Amount Due: &nbsp;</label>
                    <div class="input-group">
                        <div class="input-group-addon currency">₹</div>
                        <input value="" type="number" class="form-control" readonly="readonly" name="amountDue" id="amountDue" placeholder="Amount Due">
                    </div>
                </div>
            </span>
        </div>
    </div>
    <div class="clearfix"></div>                
</div>

——————————————–
the add row button does not auto populate the rows by fetching the data from data base while first row does the same function…the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function the add row button does not auto populate the rows by fetching the data from data base while first row does the same function

fs.readdir gets executed only at the last iteration of the loop

I’m still new to Javascript and Nodejs and I’ve been trying to access different files inside different child folders of a common parent.
Here’s what I mean by that

.
├── _captures (parent folder)
├── _folder1 (child 1)
│   ├── file1.png
│   └── file2.png
├── _folder2 (child 2)
│   ├── file1.png

So I did a for loop that iterates over each child folder and I used a nested fs.readdir which would iterate over each file in the folder.

The problem is that the fs.readdir gets called only after all the iterations and keeps looping on the last folder only.

For example if directories.length is equal to 50 it would loop over the last folder 50 times.
Here’s the script

var Directories = getDirectories('.\captures\');
for (i = 0; i < Directories.length; i++) {
   var dirtest = '.\VisualTests\' + Directories[i];
   var dirref = '.\captures\' + Directories[i];
   if (!fs.existsSync(dirtest)) {
       fs.mkdirSync(dirtest);
   }
   fs.readdir(dirref, function (err, files) {
       console.log(dirref);
       if (err) {
           console.error("Could not list the directory.", err);
           process.exit(1);
       }
       if (files.length == 0) {
           console.log("test skipped or pending");
       }
       else {
           files.forEach(function (file) {
               console.log(file);
           });
       }
   });


}

How can I make this work ?

Bearer token has been blocked by CORS policy

i have trouble with cross origin access.
When i send a request without a bearer token in Authorization header, it’s work.
When i do the same request with a bearer token, i have the following alert :

Access to XMLHttpRequest at ‘XXX/API/TEST/TEST.php’ from origin
‘http://localhost:4200’ has been blocked by CORS policy: Response to
preflight request doesn’t pass access control check: It does not have
HTTP ok status.

In my php API i have the Following header :

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Max-Age: 3600");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language,X-Authorization");

In my js script i have that :

xhr.setRequestHeader("Accept", "application/json");   
xhr.setRequestHeader("Authorization", "Bearer " + getCookie(COOKIE_NAME));
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

I have seen the folowing advice :

On the client, specify the Authorization header you want to include in the request.

On the server, respond with Access-Control-Allow-Origin header, containing the origin that performs the request, or a wildcard.

On the server, respond with Access-Control-Allow-Headers: Authorization to inform the browser that the Authorization header in the request is permitted.

But i can’t get it work.

React js handle error from request api Laravel

Hello guys I have a problem to handle error from validation Laravel
i have service class

import axios from "axios";
import { LogIn } from "react-feather";
import Alert from "../components/Alert";
import { API_BASE_URL  , BASE_URL} from "../config";

class UserService {

   async getUserInformation(id){
       try{
        const result = await axios.get(API_BASE_URL + '/getUserInformation' , { params: { id: id } })
        return result.data.users
       }catch(e){
        return false;
       }
   }

   async saveUserInfromation(user){
       try{
        const result = await axios.put(API_BASE_URL + '/update' , user )
        return result.data.users
       }catch(e){
       
        return e.response.data;
       }
   }
}

export default new UserService();

and this is my component I call the function from class service to edit user

import React, { Component } from "react";

class Clientedit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user : {},
      oldPassword: "",
      newPassword: "",
      isLoading : true,
      error : "",
    };
  }

  componentDidMount() {
  }

   handleSubmit = (e) =>{
    e.preventDefault();
    let user = this.state.user;
    try{
      const res = UserService.saveUserInfromation(user);
    
    }
    catch(e){
      
    }
  }
  }
}
export default withParams(Clientedit);

when I log error from service class I get it in my consol
enter image description here

but when I log it from my component I get nothing , any solution please