allocation in array using textinput in react native

Create a Parking Management application in React Native where the application will:
~ Parking manager can create a lot: App will ask for the number of lots in the parking area, it will
then show the number of lots on the page for the parking area.
~ Each lot will be allotted a unique number.
~ App will ask for a car registration number while entering into the parking area and allot any
random parking lot to the car, If available.
~ If no lot is empty then show a toast message that Parking is full.

  • On exit, parking charges should be paid by the car and the parking lot will also be marked
    empty for other cars, Calculations for parking charges are:

  • First 2 hour

  • $10 will be changed for every hour then after

    this is my task and i did this

    my mainpage code
    export default class mainPage extends React.Component<any, any> {
    addValues: any
    parkingLot: any
    constructor(props: any) {
    super(props)
    this.state = {
    text: ”,
    slots: [],
    screen: ‘screen1’,
    vehicleNumber: ”,
    parkingLot: [],
    selectedSlot: ”,
    }
    }

    createSlot() {
      let tempdata: any[] = []
      for (let i = 0; i < parseInt(this.state.text); i++) {
        tempdata.push({
          allocated: false,
          timestamp: new Date(),
        })
      }
      this.setState(
        {
          slots: [
            ...this.state.slots,
            {
              id: (Math.random() + 1).toString(36).substring(7),
              count: parseInt(this.state.text),
              data: tempdata,
            },
          ],
          text: '',
          screen: 'screen2',
        },
        () => {
          this.props.navigation.navigate('floor', {
            slots: this.state.slots,
          })
        },
      )
    }
    
    park = () => {
      console.log('jcjhj', this.state.parkingLot)
      var item = this.state.slots[
        Math.floor(Math.random() * this.state.slots.length)
      ]
      console.log('Parkinglot', this.state.parkingLot, item)
      console.log('Slots', this.state.slots)
      if (this.state.slots) {
      }
    }
    renderItem(item: any) {
      return (
        <TouchableOpacity
          style={styles.Slotinput}
          onPress={() =>
            this.setState({ screen: 'screen3', selectedSlot: item.id })
          }
        >
          <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
            Slot ID:-{item.id}
          </Text>
          <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
            Slot Count:-{item.count}
          </Text>
        </TouchableOpacity>
      )
    }
    renderItem1(item: any) {
      return (
        <View style={styles.Slotinput}>
          <Text>{item.allocated ? 'Allocated' : 'Available'}</Text>
          {this.state.parkingLot.map((e: any) => {
            return <Text>{e.carnumber}</Text>
          })}
        </View>
      )
      //   )
      // }
      // return demo
    }
    
    render() {
      return (
        <View>
          {this.state.screen === 'screen1' && (
            <View style={styles.form}>
              <TextInput
                style={styles.input}
                placeholder="Enter A value for slot"
                onChangeText={(text: any) => this.setState({ text })}
                value={this.state.text}
              />
              <TouchableOpacity
                style={
                  this.state.text && this.state.text
                    ? styles.addItemButton
                    : styles.BlurItemButton
                }
                disabled={this.state.text == ''}
                onPress={() => this.createSlot()}
              >
                <Text style={styles.buttonText}>Submit</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
      )
    }
    

    }

    my 2nd page code

    export default class floor extends Component<any, any> {
    handleslot: any
    constructor(props: any) {
    super(props)

          this.state = {
            text: '',
            space: props.route.params.slots,
            screen: 'screen1',
            selectedSlot: '',
          }
        }
    
        sendArray = () => {
          let tempdata: any[] = []
          for (let i = 0; i < parseInt(this.state.text); i++) {
            tempdata.push({
              allocated: false,
              timestamp: new Date(),
            })
          }
          this.setState(
            this.props.navigation.navigate('parkingSlot', {
              space: this.props.route.params.slots,
            }),
          )
          // alert(this.state.space.length)
        }
    
        renderItem = (item: any) => {
          console.log(item.item)
    
          return (
            <TouchableOpacity style={styles.Slotinput} onPress={this.sendArray}>
              <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
                Slot ID:-{item.item.id}
              </Text>
              <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
                Slot Count:-{item.item.count}
              </Text>
            </TouchableOpacity>
          )
        }
    
        render() {
          return (
            <View>
              <Text onPress={() => this.props.navigation.navigate('MainPage')}>
                Back
              </Text>
    
              <FlatList
                data={this.props.route.params.slots}
                renderItem={this.renderItem}
                keyExtractor={(item) => item.id}
              />
            </View>
          )
        }
      }
    

my 3rd page

export default class parkingSlot extends Component<any, any> {
      constructor(props: any) {
        super(props)
        // console.log('parkingSlots::--', this.props.route.params.space[0].data)
    
        this.state = {
          text: '',
          parkingLots: [] = this.props.route.params.space[0].data,
          screen: 'screen1',
          selectedSlot: '',
          vehicleNumber: '',
        }
      }
      park() {
        // console.log('this.state.parkinglot', this.state.parkingLots)
    
        this.state.parkingLots?.every((vehicleNumber: any) => {
          console.log(vehicleNumber)
    
          if (vehicleNumber.isAllocated !== true) {
            vehicleNumber.isAllocated == true
            return false
          }
          return true
        })
        this.setState([...this.state.parkingLots])
      }
    
      renderItem = (item: any) => {
        console.log('Data', item)
    
        return (
          <TouchableOpacity style={styles.Slotinput}>
            <Text>{item.allocated}</Text>
          </TouchableOpacity>
        )
      }
      render() {
        return (
          <View>
            <Text onPress={() => this.props.navigation.goBack()}>Back</Text>
            <TextInput
              placeholder="Vechicle Number"
              style={styles.input}
              value={this.state.vehicleNumber}
              onChangeText={(vehicleNumber: any) =>
                this.setState({ vehicleNumber })
              }
              // onChangeText={data => this.setState({ vehicleNumber: data })}
            ></TextInput>
            <TouchableOpacity
              style={styles.addItemButton}
              onPress={() => this.park()}
            >
              <Text>Park Vechicle</Text>
            </TouchableOpacity>
    
            <FlatList
              data={this.props.route.params.space[0].data}
              renderItem={this.renderItem}
              keyExtractor={(item) => item.id}
            />
          </View>
        )
      }
    }

Cannot read properties of null (reading ‘innerHTML’) Even With Script Tag After All Elements In My Body Tag

I keep getting the Uncaught TypeError: Cannot read properties of null (reading ‘innerHTML’) error in my console with the script tag at the end of my body tag beneath all divs and other elements. The error is only on user & opponent divs in the HTML and with the userPic.innerHTML and oppPic.innerHTML

  <body>

        <div class="container">

            <div class="header">
                <h1 class="title">Codys Pokemon Game</h1>
            </div>

            <div id="game" class="game">
                <input class="gameBtn" type="button" onclick="choose1()" value="CLICK TO START">
                <input class="infoBtn" type="button" onclick="info()" value="CLICK FOR GAME INFO">
            </div>

            <div class="user"></div>
            <div class="opponent"></div>

        </div>
    <script src="script.js"></script>
  </body>

My script.js file shouldn’t have any errors but if it does, this is the part where I add a bunch of stuff to my HTML:

    gameHTML.innerHTML = `<h2 class="gameInfo">Choose Your Attack</h2>`
    gameHTML.innerHTML += `<div class="userHp"><br>Your Health: ${pokemon1[1]}</div>`
    gameHTML.innerHTML += `<input class="att1" type="button" onclick="attack1()" value="Use: Attack: ${curPmon[4]}">`
    gameHTML.innerHTML += `<input class="att2" type="button" onclick="attack2()" value="Use: Attack: ${curPmon[5]}">`
    gameHTML.innerHTML += `<input class="att3" type="button" onclick="attack3()" value="Use: Attack: ${curPmon[6]}">`
    gameHTML.innerHTML += `<div class="oppHp"><br>Opponent Health: ${curOpp[1]}</div>`
    userPic.innerHTML += curPmon[7]
    oppPic.innerHTML += `<img src="${curOpp[7]}" alt="${curOpp[0]}">`

These are the variables I have for the IDs:


var gameHTML = document.getElementById('game')
var userPic = document.getElementById('user')
var oppPic = document.getElementById('opponent')

NodeJs data merge inside loop

I have following api data:

{
    "status": "1",
    "message": "OK",
    "result": [
        {
            "blockNumber": "14376792",
            "timeStamp": "1642218997",
            "hash": "0xe7a8a5793d1e85ec6f6de891f8be9bee2bf455b086236a98365be00febb8dec9",
            "nonce": "852",
            "blockHash": "0x45b51bbac31bd1aef3215db88d05faa1172f9b9b7cb1f8f570b67e0bcef4e954",
            "from": "0x6d038b92c6aa2fc4db2ca80dc9dc5d63ddafe33d",
            "contractAddress": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "to": "0x931b22a138893258c58f3e4143b17086a97862f6",
            "value": "72405000000000000000",
            "tokenName": "Andromeda V2",
            "tokenSymbol": "M31",
            "tokenDecimal": "18",
            "transactionIndex": "25",
            "gas": "266039",
            "gasPrice": "6000000000",
            "gasUsed": "201266",
            "cumulativeGasUsed": "2552933",
            "input": "deprecated",
            "confirmations": "670"
        },
        {
            "blockNumber": "14376072",
            "timeStamp": "1642216837",
            "hash": "0x3ffe38506478a3a81ac39933d46521aa0624cd8b89bc36f79f20c2d0b81c5f92",
            "nonce": "9",
            "blockHash": "0x672eeba6792d41c298057fefd3a31b1ab8acf8b877d8ef3f4c790234f3b4dd1b",
            "from": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "contractAddress": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "to": "0x931b22a138893258c58f3e4143b17086a97862f6",
            "value": "1917760707567583701190",
            "tokenName": "Andromeda V2",
            "tokenSymbol": "M31",
            "tokenDecimal": "18",
            "transactionIndex": "102",
            "gas": "433404",
            "gasPrice": "5000000000",
            "gasUsed": "350916",
            "cumulativeGasUsed": "17811460",
            "input": "deprecated",
            "confirmations": "1390"
        },
        {
            "blockNumber": "14375679",
            "timeStamp": "1642215658",
            "hash": "0x433638955630652e6263f14dd3322668eafe447de5ad26664a307d8283c593da",
            "nonce": "5",
            "blockHash": "0x5ab95c904b703b5b197758772bcadefa7464f2ba4528c2e9615961199ac41517",
            "from": "0x931b22a138893258c58f3e4143b17086a97862f6",
            "contractAddress": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "to": "0x7345c01c595d69a02c95d65551499c67ae3edf4f",
            "value": "620431183157188467115",
            "tokenName": "Andromeda V2",
            "tokenSymbol": "M31",
            "tokenDecimal": "18",
            "transactionIndex": "171",
            "gas": "215186",
            "gasPrice": "5000000000",
            "gasUsed": "169374",
            "cumulativeGasUsed": "34069029",
            "input": "deprecated",
            "confirmations": "1783"
        },
        {
            "blockNumber": "14375679",
            "timeStamp": "1642215658",
            "hash": "0x433638955630652e6263f14dd3322668eafe447de5ad26664a307d8283c593da",
            "nonce": "5",
            "blockHash": "0x5ab95c904b703b5b197758772bcadefa7464f2ba4528c2e9615961199ac41517",
            "from": "0x931b22a138893258c58f3e4143b17086a97862f6",
            "contractAddress": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "to": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "value": "68936798128576496346",
            "tokenName": "Andromeda V2",
            "tokenSymbol": "M31",
            "tokenDecimal": "18",
            "transactionIndex": "171",
            "gas": "215186",
            "gasPrice": "5000000000",
            "gasUsed": "169374",
            "cumulativeGasUsed": "34069029",
            "input": "deprecated",
            "confirmations": "1783"
        },
        {
            "blockNumber": "14375177",
            "timeStamp": "1642214152",
            "hash": "0x3d499ef6fe397cf121608aaff9a1c02e863fdacd41afea946f548f1f38c630df",
            "nonce": "563",
            "blockHash": "0xdceb19ad995f0cd0aae6e911744be3c6d3bf81b9e707e710bf0f06f6c1379030",
            "from": "0x931b22a138893258c58f3e4143b17086a97862f6",
            "contractAddress": "0xb46acb1f8d0ff6369c2f00146897aea1dfcf2414",
            "to": "0x6d4d24e50c1bad7df10fafb979de12b6cc6cdac8",
            "value": "1023172053263716043052",
            "tokenName": "Andromeda V2",
            "tokenSymbol": "M31",
            "tokenDecimal": "18",
            "transactionIndex": "93",
            "gas": "215186",
            "gasPrice": "5000000000",
            "gasUsed": "169374",
            "cumulativeGasUsed": "12183067",
            "input": "deprecated",
            "confirmations": "2285"
        }
    ]
}

Two rows of this data has same hash id 0x433638955630652e6263f14dd3322668eafe447de5ad26664a307d8283c593da (you can search it yourself) I want to merge some variables in this 2 rows to become one.

Here is the logic:

If rows hash are same merge (sum) value data.

My current code is like:

if(myData[id].length > 0) {
    for (let i in myData[id]) {
        const number = myData[id][i].value;
        // other values.....
        console.log('values is: ', number);
        // doing something with result
    }
}

Sample code above return value of each row in API but as I mentioned I need to sum value of rows with same hash.

Crystal clear

Based on sample API above I have 5 rows, I need to get 3 rows. One of them which data are summed up from 2 rows with same hash.

Any idea?

Using Javascript to append elements to html: is this good or can be better?

Soo, i know there must be 1000000 questions like this here, but please help me. I’m using javascript document.createElement to create containers and elements based on a sql + php database search results. I just wanna know if this is any good, or if its slow trash. It’s all working fine, but can i improve it? What is a better practice in this case? Obs.: I appended a screenshot, but if necessary i can copypaste all code.Example code

Best functional-style syntax to build this object?

The below code achieves desired output. Is there a more elegant way to do this?

For example, is there some native javascript function like flatMap etc that would help?

(I know I could get rid of the intermediate variable pieces).

const config = {
    fieldName1: {
        validation: "schema1",
        value: "abcvalue here"
    },
    fieldName2: {
        validation: "schema2",
        value: "abcvalue here"
    },
}

// Desired output: 
// {
//     fieldName1: "schema1",
//     fieldName2: "schema2",
//     ...
// }
const extractValidation = (config) => {
    const pieces = Object.entries(config).map(
        ([key, val]) => ({
            [key]: val.validation
        })
    )
    return Object.assign({}, ...pieces)
}


extractValidation(config)

Javascript on Google Sheets

So I created this script that retrieves the number of followers a playlist has on Spotify, and returns it to a cell in Google sheets. However, after working for over a year it is now broken and I can’t put my finger on why.

Here’s the script:

function SAMPLE(url) {
 const res = UrlFetchApp.fetch(url).getContentText();
 const v = res.match(/followers":({[sSw]+?})/);
 return v && v.length == 2 ? JSON.parse(v[1].trim()).total : "Value cannot be 
 retrieved.";
}

Then I have the URL in a cell and next a simple formula of =SAMPLE(A1)

Here’s the error I’m getting: SyntaxError: Unexpected end of JSON input (line 4).

Any help or guidance would be highly appreciated.

Thank you!

How to regex replace a query string with matching 2 words?

I have a url and I want to replace the query string. For example

www.test.com/is/images/383773?wid=200&hei=200

I want to match the wid= and hei= and the numbers don’t have to be 200 to replace the whole thing so it should look like this.

Expected
www.test.com/is/images/383773?@HT_dtImage

So I’ve tried doing but it only replaced the matching wei and hei.

const url = "www.test.com/is/images/383773?wid=200&hei=200"

url.replace(/(wid)(hei)_[^&]+/, "@HT_dtImage")

What should be the best approach for this algorithm? DFS or BFS? and why?

When planting flowers in a pot, it’s important to make sure
that whenever you water your plant any water that doesn’t
get absorbed by the roots drains out the bottom of the pot.
Otherwise, the water will pool in the bottom of the pot and
cause your plant to rot.

You recently decided to plant some flowers of your own,
and decided to fill the base of the pot with gravel. You've
decided to write code to verify whether water will
successfully drain out of the pot.
Using a 2D array to represent your pot, individual pieces of
gravel are notated with a 1 and empty spaces between
gravel are notated with a 0.
Example Pot #1:

[
[0, 1, 1, 1, 1],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 1, 1, 0],
[1, 0, 0, 1, 0],
]

Write a function to determine whether the water can fall
from the top row to the bottom, moving through the
spaces between the gravel. Taking the example pot from
above, you can see the posible path, which is marked by
replacing the relevant 0's with asterisks (*)

[
[*, 1, 1, 1, 1],
[*, 1, *, *, *],
[*, *, *, 1, *],
[1, 1, 1, 1, *],
[1, 0, 0, 1, *],
]

Notice that the path includes both the top and bottom
rows.
Allowed moves:
The only moves allowed are up, down, left, and right.
Diagonals are not allowed.

Here are a few pots that don't drain properly, along with
explanations.

[
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
]

Explanation: The top row has no gaps

[
[1, 1, 1],
[1, 1, 0],
[1, 1, 1],
]

Explanation: The bottom row has no gaps
[
[1, 1, 1],
[1, 1, 0],
[1, 1, 1],
]

Remove attributes when cloning an element

I have a div with multiple videos that when hovered on the video triggers a popover that contains the video that was hovered on. The problem I’m having is I’m cloning the video in the main div and appending it to the popover but when I clone the video it also clones the attributes of the video tag. What I want is when cloning the video before appending to popover removing the attribute autoplay and controls so that the video in the popover won’t play when hovered on the video. Is this possible? How can I remove the attribute before appending it to popover? Note: The main video tag needs the autoplay and controls attribute because I want it to start on load and also have controls.

I tried: $('video).attr("autoplay", "") and $('video).attr("autoplay", "false")

function appendImg() {
  const newId = parseInt($('.infoBar').children().last().attr('id').replace('test', ''))
  $('.infoBar').append('<div class="imgWrap" id="test' + (newId + 1) + '"><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" controls autoplay/></div>')
  addEvent();
}

var popOverSettings2 = {
  selector: '.infoBar .imgWrap',
  container: 'body',
  html: true,
  trigger: "manual",
  placement: 'top',
  sanitize: false,
  animation: false,
  content: function() {
    setTimeout(() => {
      $('.popover').css({
        'width': '20%',
        'height': '20%',
        'overflow': 'auto'
      })
    })
    if ($(this).attr('class') == 'imgWrap') {
      const currnetInfoBarElementView = $(this).attr('id')
      let source = $("#" + currnetInfoBarElementView).children()

      $('.infoBarPopoverContent').empty().append('<div class="infoBarElementContentView"></div>')
      $('.infoBarElementContentView').empty().append(source.clone(true).addClass('dataDisplayClone'))
      $('.dataDisplayClone img').css({
        'width': '100%',
        'height': '100%'
      })
      return $('.infoBarPopoverContent').html();
    }
  }
}


function addEvent() {
  $(function() {
    $('.infoBar .imgWrap').popover(popOverSettings2)
      .on("mouseenter", function() {
        var _this = this;
        $(this).popover("show");
        $(".popover").on("mouseleave", function() {
          $(_this).popover('hide');
        });
      }).on("mouseleave", function() {
        var _this = this;
        if (!$(".popover:hover").length) {
          $('.popover').popover('hide');
        }
      });
  });
}

addEvent()
button {
  position: absolute;
  top: 0%;
  left: 0%;
}

.infoBar {
  display: flex;
  flex-direction: row;
  position: absolute;
  top: 30%;
  max-width: 95%;
  height: 160px;
  margin: auto;
  column-gap: 25px;
  background-color: green;
  overflow-x: auto;
}

.infoBar .imgWrap {
  height: 100%;
  cursor: pointer;
}

.infoBar .imgWrap video {
  height: 100%;
  cursor: pointer;
}

.infoBarPopoverContent {
  display: none;
}

.popover .popover-body {
  overflow-x: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<button onclick='appendImg()'>Click to append img</button>

<div class="infoBar" id="infoBar">
  <div class="imgWrap" id='test1'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
  <div class="imgWrap" id='test2'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
  <div class="imgWrap" id='test3'><video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" controls autoplay /></div>
</div>

<div class="infoBarPopoverContent"></div>

Upgrade webpack, getting GET http://localhost:3000/assets/js/customEvent.js net::ERR_ABORTED 404 (Not Found)

I’m updating my react project and after I updated webpack – I’m getting the following error

login:19 GET http://localhost:3000/assets/js/vendor/modernizr.min.js net::ERR_ABORTED 404 (Not Found)
login:20 GET http://localhost:3000/assets/js/customEvent.js net::ERR_ABORTED 404 (Not Found)
login:20 GET http://localhost:3000/assets/js/customEvent.js net::ERR_ABORTED 404 (Not Found)

My index html is:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <meta name="HandheldFriendly" content="True">

  <meta name="author" content="XXX">

  <meta name="description">


  <link rel="shortcut icon" href="favicon.ico">

  <!-- VENDOR STYLES-->

  <link href="/assets/css/vendor/formValidation.css" media="all">

  <link href="/assets/css/vendor/dataTables.bootstrap4.css" media="all">

  <link href="/assets/css/vendor/responsive.bootstrap.min.css" media="all">

  <!-- REQUIRED BASE STYLES (INCLUDES BOOTSTRAP 4 FRAMEWORK STYLES)-->


  <script src="/assets/js/vendor/modernizr.min.js" type="text/javascript"></script>

  <script src="/assets/js/customEvent.js" type="text/javascript"></script>

  <base href="/" />

  <title>Title</title>

</head>

<body style="-webkit-print-color-adjust:exact;">

  <div id="app-root" class="page-wrapper">

  </div>

</body>

</html>


My webpack is as follows. I’m using the copy plugin to move assets to /assets, however, when I’m pointing to where they originally were, it still shows an error.
My CSS files were also complaining but when I removed rel="stylesheet".

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const webpack = require("webpack");
const ESLintPlugin = require("eslint-webpack-plugin");

module.exports = {
  output: {
    publicPath: "/",
    filename: "[name].[fullhash].js"
  },
  entry: {
    main: "./src/Index.jsx",
    appcss: "./src/styles/scss/app.scss",
    customcss: "./src/styles/custom/main.scss"
  },
  module: {
    rules: [
      // Javascript and JSX
      {
        test: [/.js$/, /.jsx$/],
        exclude: /node_modules/,
        use: ["babel-loader"],
        resolve: {
          extensions: [".js", ".jsx"]
        }
      },
      // SASS scss files
      {
        test: [/.css$/, /.scss$/],
        use: ["style-loader", "css-loader", "sass-loader"]
      },
      // Fonts
      {
        test: /.(woff2?|gif|ttf|otf|eot|svg|png|jpg)$/,
        type: "asset/resource",
        // generator: {
        //   filename: "fonts/[name][ext][query]"
        // }
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      APP_VERSION: JSON.stringify(process.env.npm_package_version)
    }),
    new CopyPlugin({
      patterns: [
        { from: path.resolve(__dirname, "src/assets"), to: path.resolve(__dirname, "assets") },
        { from: path.resolve(__dirname, "src/styles/custom/assets"), to: path.resolve(__dirname, "assets/custom") }
      ]
    }),
    new CaseSensitivePathsPlugin(),
    // Generates HTML file output with the bundles referenced in <script> and <link> elements
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    }),
    new ESLintPlugin({
      extensions: ["js", "jsx"],
    })
  ],
  resolve: {
    alias: {
      app: path.join(__dirname, "src"),
      "app-api": path.join(__dirname, "src/api"),
      "app-version": path.join(__dirname, "src/config/version.js")
    }
  }
};

Any help appreciated.

Iterate over JS object of arrays

I have this object that I’m trying to loop over in a form but really can’t get it to work. Here is sample of the object.

        const data = {
            "Social Security": [
                {
                    label: "Deduction Type", 
                    value: "Social Security", 
                    name: "SocialSecurity"
                },
                {
                    label: "Employer Rate", 
                    value: "12.4%", 
                    name: "SocialEmployer"
                },
                {
                    label: "Employee Rate", 
                    value: "6.2%", 
                    name: "SocialEmployee"
                }
            ],
            "Medicare": [
                {
                    label: "Deduction Type", 
                    value: "Medicare", 
                    name: "Medicare"
                },
                {
                    label: "Employer Rate", 
                    value: "1.45%", 
                    name: "MedicareEmployer"
                },
                {
                    label: "Employee Rate", 
                    value: "2.9%", 
                    name: "MedicareEmployee"
                }
            ]
        }

form implementation

        <Formik>
            {({ values, isSubmitting, resetForm, setFieldValue }) => (
            <Form id="payrollSettingsForm" >                        
                <Grid container className={classes.border}>
                    <Grid item xs={12} md={4}>
                        {Object.entries(data).map(arr =>{
                            Array.isArray(arr) && arr.map(elm =>{
                                return (<TextField 
                                    label={elm.label} 
                                    value={elm.value}  
                                    name={elm.name}  
                                />)
                            })
                        })}
                    </Grid>
                </Grid>

        ...rest of the form 
            </Form>
        </Formik>

Tried many approaches like Object.fromEntries(). forEach I think all the methods I can find example and keep failing, maybe I’m doing something wrong, any help will be appreciated.

Can you add an action to an element within the tooltip in chart.js?

I have a line chart drawn with chart.js that shows some data.
I’ve added a delete element within the tooltip, but I don’t know if it’s possible to add an interaction, so that when I click the delete element, within the tooltip, some custom code is run that deletes the data from the Data base.

const weight_graphOptions = {
  title: {
    text: 'Weight',
    display: true
  },
  scales: {
    x: {
      type: 'time',
      time: {
        // Luxon format string
        tooltipFormat: 'dd-MM-yyyy'
      },
      title: {
        display: true,
        text: 'Date'
      }
    },
    y: {
      title: {
        display: true,
        text: 'kg'
      }
    }
  },
  plugins: {
    tooltip: {
      events: ['click'],
      callbacks: {
        afterFooter:
          function (addDeleteButton) {
            return 'Delete'
          }
      }
    }
  }
}

Does anyone know if I can do this without building my own custom-made tooltip?

How do I submit a form on an onChange Event without submit button

How do I submit a form on an onChange event of an tag, with without triggering the default behaviour(Page reload). I found out, that I can access the form from the event with the .form element. But if I trigger .form.submit() the page reloads although I have stated on:submit|preventDefault.

I prepared an example of my Problem:
https://svelte.dev/repl/894212c7c3d847dd961745f5e9d5750a?version=3.46.2

Also is there like a clean/correct/best-practice way of solving this, without using an submit button?

Thanks in advance for your help!