var existData = props.quotes.find((obj) => obj.id === params.id); find is undefined

var existData = props.quotes.find((obj) => obj.id === params.id); find is undefined

Fetching data from firebase, displaying data in quote list, and single quote page,

using props,

Using react-dom

const AllQuotes = (props) => {
  const [movies, setMovies] = useState([]);

  async function movieData() {
    try {
      const response = await fetch(
        "https://react-post-api-default-rtdb.firebaseio.com/NewQuotes.json"
      );
      const data = await response.json();
      const loadedData = [];
      for (const key in data) {
        loadedData.push({
          id: key,
          // id : Math.random(0,1).toString(),
          author: data[key].author,
          quote: data[key].quote,
        });
      }
      setMovies(loadedData);
    } catch (error) {}
  }

  useEffect(() => {
    movieData();
  }, []);

  return (
    <React.Fragment>
    <div>
      <h1>All Quotes</h1>
      {/* <button onClick={movieData}>fetch data</button> */}
      <QuoteList quotes={movies} />
    </div>

      <QuotesDetail quotes={movies} />

    </React.Fragment>
  );
};

Single quote display page

const QuotesDetail = (props) => {
  const params = useParams();
  const match = useRouteMatch();

  // console.log(match)

  // console.log(params.id)

  var existData = props.quotes.find((obj) => obj.id === params.id);```




Getting error find is undefined. 

Issue deleting rows locally with react redux

In the below slice code I am Getting the data from a server using createAsyncThunk. Now I am trying to delete data locally for which I have written a reducer called removeData.

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

export const dataTableSlice = createSlice({
  name: "dataTable",
  initialState: {
    isGridData: [],
    isLoading: false,
  },
  reducers: {
    removeData: (state, action) => {
      const dataSource = [...state.isGridData];
      const filteredData = dataSource.filter(
        (item) => item.id !== action.payload.id
      );
      state.isGridData.push(filteredData);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(loadData.pending, (state, action) => {
        state.isLoading = true;
      })
      .addCase(loadData.fulfilled, (state, action) => {
        state.isGridData = [...action.payload.data];
        state.isLoading = false;
      });
  },
});

export const loadData = createAsyncThunk("loadData", async () => {
  return await axios.get("https://jsonplaceholder.typicode.com/comments");
});

export const { removeData } = dataTableSlice.actions;

export default dataTableSlice.reducer;

Component

import { Table,Popconfirm,Button } from 'antd';
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {loadData,removeData} from '../../features/DataTableState/DataTableSlice';
import "antd/dist/antd.css";
import './DataTable.scss';


const DataTable = () => {

  const gridData = useSelector((state) => state.dataTable.isGridData);
  const isLoading = useSelector((state) => state.dataTable.isLoading);
  const dispatch = useDispatch();


  
  useEffect(() => {
    dispatch(loadData());
  },[dispatch]);

  const inventoryData = gridData.map((item) => ({
    ...item,
     inventory:Math.floor(Math.random() * 6) + 20,
  }));

  const modifiedData = inventoryData.map(({body,...item}) =>({
    ...item,
    key:item.id,
    message:body,
  }));

  // const handleDelete = (record) =>{
  //   const dataSource = [...modifiedData];
  //   const filteredData = dataSource.filter((item) => item.id !== record.id);
  // }


  const columns = [
    {
      title:'Id',
      dataIndex:'id',
      align:'center',
    },
    {
      title:'product',
      dataIndex:'name',
      align:'center',
      editTable:true
    },
    {
      title:'description',
      dataIndex:'message',
      align:'center',
      editTable:true
    },
    {
      title:'inventory',
      dataIndex:'inventory',
      align:'center',
      editTable:false
    },
    {
      title:'Action',
      dataIndex:'action',
      align:'center',
      render: (_,record) =>
      modifiedData.length >= 1 ? (
        <Popconfirm title="Are you sure?" onConfirm={dispatch(removeData(record))}>
          <Button danger type='primary'>Delete</Button>
        </Popconfirm>
      ):null,
    },

  ];

  // const data = [
  //   {
  //     Id:1,
  //     product:'gas1',
  //     description:'18kg',
  //     inventory:52,
  //   },
  //   {
  //     Id:2,
  //     product:'gas1',
  //     description:'18kg',
  //     inventory:52,
  //   },
  //   {
  //     Id:3,
  //     product:'gas1',
  //     description:'18kg',
  //     inventory:52,
  //   },
  //   {
  //     Id:4,
  //     product:'gas1',
  //     description:'18kg',
  //     inventory:52,
  //   }
  // ]

  return (
    <div className='data-table'>
      <section className='space'></section>
     <Table 
     className='table'
     columns={columns}
     dataSource={modifiedData}
     bordered
     loading={isLoading}
     style={{flex:2}}/>
    </div>
  );
}

export default DataTable

Below given are errors in console:

1.serializableStateInvariantMiddleware.ts:195 A non-serializable value was detected in an action, in the path: payload.config.adapter. Value:
Take a look at the logic that dispatched this action: {type: ‘loadData/fulfilled’, payload: {…}, meta: {…}}

2.Warning: Cannot update a component (DataTable) while rendering a different component (Cell). To locate the bad setState() call inside Cell, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

How to import data to SQL where some of the data were imported from CSV and some of it will be retrieved based on the user’s id?

I have a SQL table with dynamic form where I need to import the data for the dynamic form from the user. Each tenant will have a table with their id and the dynamic form is to store the contacts for each of their customer.

How do I input the tenant_id, user_id, organization_form_customer_id and date_created as these data won’t be included in the CSV. I’ll be retrieving it from the user login data. and since the form is dynamic the number of form_idNum will be different for each tenant.

Eg; tenant_id = 33 will have form_id96 – form_id113 while tenant_id = 34 will have form_id114 – form_id131. but if tenant_33 add a new column for the dynamic form, the form_idNum will be form_id132 where it continues from the last form_idNum from tenant_34.

Dynamic Form’s table

form_customer_33 table

form_customer_34 table

CSV file

For now I’ve managed to import data from csv with this hardcode ==”

the route (to retrieve data from user):

router.post('/import-contacts', auth, async (req, res) => {     
  let user_id = req.user.user_id;                // = 66
  let tenant_id = req.user.tenant_id;            // = 33
  let tableName = "form_customer_" + tenant_id;  // = form_customer_33
  let organization_form_customer_id = req.user.organization_form_customer_id;  // = 1
  let importedData = req.files;
  let filePath = attachmentConfig.uploadpath + '/' + req.files[0].filename;      
  let results = importExportCsv.insertData(filePath, tableName, tenant_id, user_id);    
  res.status(200).send("Data imported successfully");
});

the model:

importExportCsv.insertData = (filePath, tableName, tenant_id, user_id) => {
    const datetimenow = DateTime.now();
    const currentdatetime = datetimenow.toFormat('yyyy-MM-dd HH:mm:ss');            
    let stream = fs.createReadStream(filePath);
    let csvData = [];
    let csvStream = csv
        .parse()
        .on("data", function(data) {
            csvData.push(data);
        })
        .on("end", function() {             
            // Remove header row
            csvData.shift();                
            return new Promise((resolve, reject) => {    
                pool.query(`INSERT INTO ${tableName} (form_id114, form_id115, form_id116, form_id117, form_id120, form_id121, form_id123, form_id125, form_id127, form_id129, form_id131) VALUES ?`, [csvData], (err, results) => {
                    if(err) {
                        console.log("Error: ", err);
                        return reject(err);
                    }
                    return resolve(results);
                });
            });         
        }); 
    stream.pipe(csvStream);
};

What I want is something like this =>

pool.query(`INSERT INTO ${tableName} tenant_id, user_id, organization_form_customer_id, date_created, dynamic_form VALUES ?`, [tenant_id, user_id, organization_form_customer_id, currentdatetime, csvData]

How do I achieve this? Thank you for the help

How to parse and append to XML file a new content?

I have an hardcoded XML file I need to parse and append some content.

This is the file:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent"><![CDATA[{
  "keyToString": {
    "RunOnceActivity.OpenProjectViewOnStart": "true"
  }
}]]></component>
</project>

My Target is to convert it to:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent"><![CDATA[{
  "keyToString": {
    "RunOnceActivity.OpenProjectViewOnStart": "true",
    "test": 5
  }
}]]></component>
</project>

I have the following JS code to do so:

const path = require('path');

const fs = require('fs-extra');
const xml2js = require('xml2js');

const xmlFilePath = path.join(__dirname, './resource.xml');
const xmlFileDestPath = path.join(__dirname, './resource-new.xml');

(async () => {
    const xmlContent = await fs.readFile(xmlFilePath, 'utf-8').catch(() => '');
    const parsedXml = await xml2js.parseStringPromise(xmlContent);

    const objectToAppend = parsedXml['project']['component'][0]['_'];
    const parsedObject = JSON.parse(objectToAppend);
    const parsedKeyToString = parsedObject['keyToString'];

    const newObject = { ...parsedKeyToString, test: 5 };

    parsedXml['project']['component'][0]['_'] = JSON.stringify({ keyToString: newObject });

    const builder = new xml2js.Builder({
        xmldec: { version: '1.0', encoding: 'UTF-8' },
        cdata: true,
    });

    const workspaceXmlFileContent = builder.buildObject(parsedXml);

    await fs.writeFile(xmlFileDestPath, workspaceXmlFileContent);
})();

But the output file is:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PropertiesComponent">{"keyToString":{"RunOnceActivity.OpenProjectViewOnStart":"true","test":5}}</component>
</project>

Not exactly what I wanted. Where is my problem?

Google app script delete event from 2 possible calendar

I would like to delete calendar event form 2 possible calendar. I try to define 2 calendar IDs using OR || but if calendar id return null on first try the deleteevent become error. Anyone can help?

var calendarId = "calendarID1" || "calendarID2" ;
var eveId = 2;
//var typeId = 3;

function deleteEvent() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  var lr = rows.getLastRow();

  var eventID = sheet.getRange(lr, eveId, 1, 1).getValue();
  //var type = sheet.getRange(lr, typeId, 1, 1).getValue();

  var cal = CalendarApp.getCalendarById(calendarId);
  var event = cal.getEventSeriesById(eventID);
  event.deleteEventSeries();

}

Can I add functionality to this incrementor?

I am still learning JavaScript so I wanted to use this as an added opportunity to learn more.
Currently, the code is written in only HTML & CSS. Where I need help is in making this work with JavaScript.

I saw a number incrementor/decrementor (like the one used to include more items or less into a shopping cart), and I was trying to imitate this cool stuff. But, I am not very sure how to code the Vanilla JS to make it work.

There are 5 slides in the incrementer, I just want the plus and minus buttons to work.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  width: 100%;
  height: 100vh;
  background-color: #888888;
  display: grid;
}

div.body {
  align-self: center;
  justify-self: center;
}

div.body div.inner {
  display: flex;
  height: 60px;
  width: fit-content;
  column-gap: 10px;
}

div.body div.inner div.num_slides {
  background-color: #409bd0;
  display: flex;
  height: inherit;
  width: 60px;
  overflow: hidden;
  font-family: 'Yu Gothic UI';
}

div.body div.inner div.num_slides div.num {
  display: flex;
  align-items: center;
  justify-content: center;
  height: inherit;
  min-width: 60px;
  font-size: 40px;
  font-weight: 600;
}

div.body div.inner div.btn {
  background-color: #d0d0d0;
  height: 100%;
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  font-weight: 900;
  color: #333333;
}

div.body div.inner div.btn:hover {
  background-color: #d0d0d0;
  cursor: pointer;
}

div.body div.inner div.btn.deactivated {
  opacity: 0.6;
  cursor: not-allowed;
}
<div class="body">
  <div class="inner">
    <div class="btn deactivated" id="minus">
      <span>&minus;</span>
    </div>
    <div class="num_slides">
      <div class="num">1</div>
      <div class="num">2</div>
      <div class="num">3</div>
      <div class="num">4</div>
      <div class="num">5</div>
    </div>
    <div class="btn" id="plus">
      <span>&plus;</span>
    </div>
  </div>
</div>

Please help me out, guys. Thank You!

Compare Objects in Array [closed]

i have this array and I want to compare every object parentid with another object id
in same array

var array = [
    { id: 1, parentid: 2 },
    { id: 2, parentid: 2 },
    { id: 3, parentid: 2 },
    { id: 4, parentid: 5 },
];
let isparent = array.every(function (val, i, arr) {
    return val.id === array[0].parentid;
});

console.log(isparent);

this codes doesn’t work for me !

How to get text nodes and tagged nodes out of contents of a Div element in javascript? [duplicate]

I have included some textual content in a div element. I want to access individual nodes out of it in the form of strings.
Some nodes are tagged in bold, and therefore the rest of nodes that are formed in the text are non-tagged. I am trying to access all the individual nodes thus formed using nodeList, or through a simple indexed loop using childNode property. I have even used document.queryselectorAll(), but nothing seems to work.Following is the code snippet:

<!DOCTYPE html>
<html>
  <body>
  <div id="mydiv" class="myDiv" contenteditable="true">This <b>life</b> is my choice, <b>anyway</b> I know how to lead a good one!!!</div>
</body>
<script>
 let myString ='';
            for(let i=0; i<mydiv.childNodes.length;i++){
         myString = mydiv.childNodes[i]+mydiv.childNodes[i+1]+mydiv.childNodes[i+2]
       }
console.log(myString)
</script>
</html>

I’m getting this at the console:
[object Text][object HTMLElement][object Text]

getting error in showing markers on the leaflet map

I am using leaflet map with my data in a csv file for markers. the markers don’t appear on map. cant sort the problem.

map.js

'''

let path = "data/ppv_full.csv";

// create the map
function createMap(){
    map = L.map('map').setView([0,0],3);


// function to read csv data
function readCSV(){
    Papa.parse(path, {
        header: true,
        download: true,
        complete: function(data) {
            console.log(data);
            
            // map the data
            mapCSV(data);

        }
    });
}

function mapCSV(data){
    
    // loop through each entry
    data.data.forEach(function(item,index){
        // create marker
        let marker = L.marker([item.latitude,item.longitude])

        // add marker to featuregroup
        markers.addLayer(marker)
    })

    // add featuregroup to map
    markers.addTo(map)

    // fit markers to map
    map.fitBounds(markers.getBounds())
}
''' 

this is the error i am getting in the console:

LatLng.js:32 Uncaught Error: Invalid LatLng object: (undefined, undefined)
    at new D (LatLng.js:32:9)
    at j (LatLng.js:123:11)
    at i.initialize (Marker.js:102:18)
    at new i (Class.js:22:20)
    at t.marker (Marker.js:385:9)
    at map.js:42:18
    at Array.forEach (<anonymous>)
    at mapCSV (map.js:40:12)
    at Object.complete (map.js:31:4)
    at l.parseChunk (papaparse.min.js:7:6757)

the HTML page only shows the map without any markers.

retrieve multiple schemas without ref

enter image description here

Hello.
I would like to ensure that when I recover my “products I would also like to recover
“admin_address”, “likes”. AND also for the same with likes and admin.

I can retrieve that admin car products has its ref:

I based myself on “BandSchema.virtual()” but I don’t know if it’s possible to do the count option several times for each Schema.

Thanks

Import/Export error: The requested module does not provide an export named ‘pageFlip’

I recently switched over to the new Vite compiler for Laravel. I noticed that it somehow did not accept my window object anymore. No problem I thought, I’ll just use imports/exports. However, I just keep getting the same error:

The requested module '../../../../../js/plugins/pageflip.js' does not provide an export named 'pageFlip'

I have searched all over the internet, but it keeps telling me not to confuse named exports/imports with default ones. However, I don’t see anything wrong with my code. Could someone please help me with this?

show.blade.php

<div>
   HTML HERE
</div>

@push('scripts')
    <script type="module">
        import {pageFlip} from "../../../../../js/plugins/pageflip.js";

        @isset(condition here)
            pageFlip.turnToPage({{ $tale->taleUser->progress }})
        @endisset

        @can(condition here)
            pageFlip.on('flip', (e) => {
                document.getElementById('pageProgress').value = pageFlip.getCurrentPageIndex();
                document.getElementById('pageCount').innerHTML = pageFlip.getCurrentPageIndex();
            });
        @endcan

        function turnPage(bool) {
            if (bool) {
                return pageFlip.turnToNextPage();
            }

           return pageFlip.turnToPrevPage();
        }
    </script>
@endpush

My script file:

import {PageFlip} from 'page-flip'

const pageFlip = new PageFlip(document.getElementById('book'),
{
    width: 400,
    height: 600,
    size: ('stretch'),
    minWidth: 200,
    minHeight: 400,
    maxWidth: 1000,
    maxHeight: 1000,
    autoSize: true,
    disableFlipByClick: true,
    showCover: false
}
);

pageFlip.loadFromHTML(document.querySelectorAll('.tale-page'));

export { pageFlip }

The vite config file:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
plugins: [
    laravel([
        'resources/css/app.css',
        'resources/js/app.js',
        'resources/js/plugins/pageflip.js',
    ]),
],
});

Judging by the error, I am a bit confused. I really am providing an export named ‘pageFlip’, right? Or am I possibly missing some vite configuration?

I am using the StPageFlip package provided by Nodlik.

Is there a way to use React Hooks without create-react-app?

I normally use ‘npx create react app’ but I was just wondering if there is a way to do something like this.

<div id="root"></div>
<script type="text/babel">

    import { useState } from 'react' // you can't do it like this, adding script tag and adding babel and react on the top 

    const TodoList = () => {

        const [todos, setTodos] = useState([]);
        return (
            <h1>Todo App</h1>
        )
    }

    const App = () => {
        return (
         <TodoList/>   
        )
    }

    const root = ReactDOM.createRoot(
        document.getElementById("root")
    )
    root.render(<App/>)

</script>

Implementing a zoom function but can’t get it to work properly

    let scale = 1;
    let translateX = 0;
    let translateY = 0;
    let element = document.querySelector('img');

    let zoom = ( e ) => {

        e.preventDefault();

        let formerScale = scale;
        scale -= (e.deltaY / 5000);
        let elemRect = element.getBoundingClientRect();
        let mX = e.clientX - elemRect.x;
        let mY = e.clientY - elemRect.y;

        let newMX = mX - translateX ;
        let newMY = mY - translateY;
        
        let x = mX - (newMX * (scale / formerScale));
        let y = mY - (newMY * (scale / formerScale));
        translateX = x;
        translateY = y;

        element.style.transform = `translate(${x}px, ${y}px) scale(${scale})`;

    }
    element.addEventListener('mousewheel', wheelZoom);

I am having trouble getting this zoom based on mouse position to work. I got this image with a 3:2 aspect ratio as the elem and the zoom isn’t behaving the way its supposed to. It is zooming, but it is traveling away from the area where the mouse is rather than adjusting to it.