I’m having a problem on ReactJS that is having a undefined in Mapping of array [duplicate]

I’m currently having a problem on javascript that is: “Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)”

I tried removing the useEffect hook, didn’t work, tried put ? after array like: array?.map. Didn’t work
You can see it right here:
`

function blabla(){
    const [itemIndex,setItemIndex] = useState(1)
    const [items, setItems] = useState()
    useEffect(function(){
        function success1(data){
            setItems(data)
        }
        var def ={
            type: "GET",
            url: "http://localhost:3001/blabla",
            success: success1
        }
        jQuery.ajax(def)
    }, [])
    return(
        <>
            <Navbar/>
            <section className="items">
                <div className="items-col">{
                    items.map(function(element){
                        if((itemIndex-1)%3 === 0){
                            setItemIndex(itemIndex+1)
                            return <span>{element.name}</span>
                        }
                        return null
                    })
                }</div>
                <div className="items-col">{
                    items.map(function(element){
                        if(itemIndex%3 === 2){
                            setItemIndex(itemIndex+1)
                            return <span>{element.name}</span>
                        }
                        return null
                    })
                }</div>
                <div className="items-col">{
                    items.map(function(element){
                        if(itemIndex%3 === 0){
                            setItemIndex(itemIndex+1)
                            return <span>{element.name}</span>
                        }
                        return null
                    })
                }</div>
            </section>
        </>
    )
}
export default blabla

Im I missing something on this form to get error 409 on Dev’s Console?

Hey guys im coding a website for myself and during the execution the form, im getting a 409 error on Chrome’s Developer Console, as far as I understand, error 409 seems to be a conflict error, therefore I have checked every Id, and class linkage and cant find any sort of error, maybe help me get a look?If it’s not that, then what else could it be? I see a lot of the same questions with no answers, would be great to find a solution and leave a post for it.

Here’s me code:

HTML

<div class="col-lg-7">
                        <div class="form-contact">
                            <form action="#" id="formcontact">
                                <div class="form-group row formwrap">
                                    <div class="col-lg-6 pt-5">
                                        <label for="yourname">Nombre</label>
                                        <input type="text" id="yourname" placeholder="Ingresa tu nombre" name="name" class="mt-3 input-control inputtext " data-name="name" />
                                    </div>
                                    <div class="col-lg-6 pt-5">
                                        <label for="yourmail">E-Mail</label>
                                        <input type="email" id="yourmail" placeholder="Ingresa tu e-mail" name="email" class="mt-3 input-control inputtext " data-name="email" />
                                    </div>
                                    <div class="col-lg-12 pt-5">
                                        <label for="comment">Mensaje</label>
                                        <textarea class="comentarea mt-3 input-control" id="comment" placeholder="Tienes una campaña en mente? Descríbenos como la visualizas y cuales son tus metas, así podemos ayudarte." data-name="comment" name="comment"></textarea>
                                        <button id="submitbutton" class="submitbuton button mt-5 mb-3" type="submit">Enviar Ahora</button>
                                        <div class="contactform__loader pt-3"></div>

                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

PHP:

<?php
$subject    = 'Juan,me gustaría trabajar contigo' . $_REQUEST['email']; // Subject of your email
$to    xxxx.com     = '[email protected]'; //Your e-mail address
$headers    = 'MIME-Version: 1.0' . "rn" .
              'Content-type: text/html; charset=iso-8859-1' . "rn";
$message    = 'Name: ' . $_REQUEST['name'] . ' <br/>' .
              'E-mail: ' . $_REQUEST['email'] . ' <br/>' .
              'Message: ' . $_REQUEST['comment'];
if (@mail($to, $subject, $message, $headers))
{
 echo 'your message send';
}
else
{
 echo 'failed';
}
?>

Javascript:

 // form post submit  
    const posttheform = function(e) {
        formcontact.onsubmit = async(e) => {
            e.preventDefault();
            var valid = [];
            allinputs.forEach(function(i, j) {
                if (i.getAttribute('data-name')) {
                    var checkAttr = i.getAttribute('data-name');
                } else {
                    var checkAttr = i.tagName;
                }
                var thisvalue = i.value;
                // check input valid
                switch (checkAttr) {
                    case 'name':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('<li>Please check your input name</li>');
                        } else if (thisvalue.length < 3) {
                            valid.push('<li>Sorry your name char is to short</li>');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    case 'email':
                        var regEmail = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/;
                        if (i.value == '' || !regEmail.test(i.value)) {
                            i.classList.add("error");
                            valid.push('<li>Please check your mail address input</li>');
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                    case 'comment':
                        if (thisvalue == '') {
                            i.classList.add("error");
                            valid.push('<li>Please write something</li>');
                        } else {
                            i.classList.remove("error");
                        }

                        break;
                    default:
                        if (i.value == '') {
                            valid.push('<li>Something was wrong</li>');
                            i.classList.add("error");
                        } else {
                            i.classList.remove("error");
                        }
                        break;
                };
            });
            if (valid.length) {
                information.innerHTML = `<div class="alert alert-danger" role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0"><ul class="errorlist">` + valid.join('') + `</ul></p></div>`;
            } else {
                information.innerHTML = `<div class="d-flex align-items-center"><strong class="font-weight-normal">Please wait...</strong><div class="spinner-border spinner-border-sm ml-auto" role="status" aria-hidden="true"></div></div>`;
                inputelement.setAttribute("readonly", "true");
                textareaelement.setAttribute("readonly", "true");
                buttonsubmit.setAttribute("disable", "true");
                // change the fetch address based on the mail.php file you put in your server's file directory ---------------------------
                let response = await fetch('mail.php', {
                        method: 'POST',
                        body: new FormData(formcontact)
                    })
                    .then((response) => response.text())
                    //Then with the data from the response in JSON...
                    .then((data) => {
                        if (data === 'your message send') {
                            formcontact.reset();
                            inputelement.removeAttribute("readonly");
                            textareaelement.removeAttribute("readonly");
                            buttonsubmit.removeAttribute("disable");
                            information.innerHTML = `<div class="alert alert-success  " role="alert"><h4 class="alert-heading">Message send successful !</h4> <hr><p class="mb-0">I will reply to your message soon thank you</p></div>`;
                        }
                    })
                    //Then with the error genereted...
                    .catch((error) => {
                        formcontact.reset();
                        inputelement.removeAttribute("readonly");
                        textareaelement.removeAttribute("readonly");
                        buttonsubmit.removeAttribute("disable");
                        information.innerHTML = `<div class="alert alert-danger " role="alert"><h4 class="alert-heading">There is something wrong !</h4> <hr><p class="mb-0">Sorry, your message failed to be sent due to an unknown error</p></div>`;
                    });
            }
            return false;
        };
    };

I have tried checking the id, I have tried modifying the request type, no luck

Map function in JSON array

I want to find an object from a JSON array. My code is working fine with the object found. But the issue is what if the employee id is not? My code console’s “not found” two times. Kindly guide me on what the issue is with my code.

var E_ID

let empArray = [
 {

  "employee": {
    "employee_ID": 16,
    "employee_designation": "Node.js",
     "employee_FirstName": "John",
     "employee_lastName": "Doe",
  }
 },
 {
   "employee": {
    "employee_ID": 17,
    "employee_designation": "Full Stack",
    "employee_FirstName": "Samual",
    "employee_lastName": "Smith",
  },
 }
]

 function search_EmployeeByID(E_ID) {
  empArray.find(item => {
    if (item.employee.employee_ID == E_ID) {
         console.log(item.employee)
         return true
     
   }else {
          console.log("not found")
          return false
   }

 })

}

E_ID = parseInt(prompt("Enter Employee_ID to search for:"))
search_EmployeeByID(E_ID);`

How to automate page redrawing at a certain interval using JS?

I am writing a web page for an RFID access control system, and I need to implement automatic redrawing on the main page where the last action is displayed (for example, so that you don’t have to manually refresh the page when a person has passed to see information about him).

My part of the data page:

<#macro tbody>
        <#list activities as activity>
        <tr>
            <td>${activity.scannerHardwareNum}</td>
            <td>${activity.formattedEnterActivity}</td>
            <td onclick="goTo('user/get/${activity.user.userId}')">${activity.user.surname} ${activity.user.name} ${activity.user.patronymic}</td>
        </tr>
    </#list>
</#macro>

<#macro content>
    <script>
        setInterval(() => goTo('start') , 3000)
    </script>
    <@table caption="Last activity"/>
</#macro>

At first, I tried to implement it using an ajax request:

function goTo(link) {
    $.ajax({
        url: "http://localhost:" + getPort() + "/" + link,
        type: "GET",
        success: function () {
            console.log('OK');
        },
        error: function (response) {
            console.log(this.url)
            alert(response);
        }
    })
}

But the data was not updated, I assumed that this was due to the fact that my data comes using a template engine and when redrawing the page, new data does not come, since there is no new request for them.

As a result, I implemented this simply using a JS script to navigate to the same page:

function goTo(link) {
    let port = getPort();
    console.log('http://localhost:' + port + '/' + link);
    window.location.href = 'http://localhost:' + port + '/' + link;
}

But now the page is being updated, and I would like to complete this task without updating, if it possible.

How to display No results found message on Search using Javascript only?

I am trying to display “No Results Found” in the case where someone uses my search feature to search for something that returns no results.

Currently it does not display any text if no results found. The problem is I am unable to update the HTML code, but can only update Javascript. So cannot add empty div for the message into the HTML code.

Please see the code below. Thanks in advance.

function myFunction() {
  const userInput = document.getElementById("myInput").value.toUpperCase();
  const tableRows = document.querySelectorAll("table tr");
  for (let i = 0; i < tableRows.length; i++) {
    const rowTextContent = tableRows[i].innerText.toUpperCase();
    tableRows[i].style.display = rowTextContent.toUpperCase().includes(userInput) ? "" : "none";
  }
}
table.table_brdr td {
  padding: 8px 10px;
  border: none;
}

table.table_brdr th {
  background-color: #a6a6a6;
  color: black;
}

tr:nth-of-type(odd) {
  background-color: #D3D3D3;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 20%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search forms list" title="Search forms list"></p>

<table class="table_brdr" id="myTable">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>

<tr>
<td>abc</td>
<td>xyz0</td>
<td>03/30/2017</td>
</tr>

<tr>
<td>test12</td>
<td>https://www.yahoo.com/ </td>
<td>03/30/2017</td>
</tr>
  
<tr>
<th>Column1</th>
<th> New Column</th>
<th>Column3</th>
</tr>

<tr>
<td>John</td>
<td>abctd <td>
<td>09/30/2019</td>
</tr>
  
<tr>
<th>Column1</th>
<th> New Column2</th>
<th>Column3</th>
</tr>

<tr>
<td>Doe</td>
<td>abctd </td>
<td>06/30/2019</td>
</tr>

</table>

how to create Grid have 5 coloumn and small screen 2 coloumn in reactjs?

I am trying to create Grid using material UI + reactJs.
I am following this url https://mui.com/system/react-grid/
But here there is problem we can’t able to create 5 column in Grid. so I try to create Custom Grid which have 5 column for large screen .for Medium screen need 3 column . and for mobile 2 column .

I am able to create 5 column but issue is mobile I am not able to create 2 column layout.

current output

1 2
3 4
5
11 22
33 44  

Expected output

1  2
3  4
5  11
22 33
44

here is my code
https://codesandbox.io/s/nostalgic-joliot-3xc7bo?file=/src/App.tsx

import * as React from "react";
import {
  /* the components you used */
  Typography
} from "@mui/material";
import { styled } from "@mui/material";

export const DGrid = styled("div")({
  display: "flex",
  alignItems: "flexStart",
  flexWrap: "wrap"
});

export const DGridCol = styled("div")({
  width: "calc(100% / 5 - 16px)",
  marginBottom: "24px",
  marginRight: "20px",
  "&:last-child": { marginRight: "0px" },
  "@media (max-width: 768px)": {
    width: "calc(100% / 2 - 8px)",
    marginBottom: "15px",
    marginRight: "16px",
    "&:last-child": { marginRight: 16 },
    "&:nth-child(2),&:nth-child(4),&:nth-child(6)": { marginRight: 0 }
  }
});

/**
 * how you used the components
 */
export default function App() {
  return (
    <div>
      <DGrid>
        <DGridCol>
          <div style={{ background: "red" }}>1</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>2</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>3</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>4</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>5</div>
        </DGridCol>
      </DGrid>

      <DGrid>
        <DGridCol>
          <div style={{ background: "red" }}>11</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>22</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "red" }}>33</div>
        </DGridCol>
        <DGridCol>
          <div style={{ background: "yellow" }}>44</div>
        </DGridCol>
      </DGrid>
    </div>
  );
}

How do I make the text scroll continously

I have no code to show yet because I have no idea how to do that… my question is: How do I make the text scroll continously i.e., as soon the line 9 is getting up, rather show the blank space, show the contents of line 1 and so on, so there’s no empty space. I supposed to do that with JS, I guess but I don’t know how to get those offsets or show the contents from top right after the bottom lines is moving up… my current code goes like this:

#jobs_container {
  background: transparent;
  width: 600px;
  height: 300px;
  border: 3px solid #e4e4e4;
  border-radius: 12px;
  border-style: dashed;
  padding: 1px;
  font-size: 12px;
}

#jobs_header {
  display: flex;
  justify-content: space-between;
  height: 25px;
  background-color: #e4e4e4;
  border-radius: 12px 12px 0 0;
  padding: 1rem;
}
#jobs_header_left {
  display: flex;
  align-items: center;
  
}
#jobs_header_left > span {
  padding-right: 4px;
    cursor: pointer;
  color: #0048FF;
}
#jobs_header_center {
    text-align: center;
    font: 20px Verdana;
    color: darkblue;
}

#jobs_header_right {
  display: flex;
  align-items: center;
  
}
#jobs_today {
  margin-inline: 5px;
  cursor: pointer;
  color: #0048FF;
}
#jobs_nextButton {
  background: transparent;
  border: none;
  padding: 0px 3px;
  cursor: pointer;
}

#jobs_prevButton {
  background: transparent;
  border: none;
  transform: scaleX(-1);
  padding: 0px 3px;
  cursor: pointer;
}

#jobs_content {
  font-style: calibre;
  margin-left: 10px;
  margin-top: 10px;
  position: relative;
  overflow-x: scroll;
  max-height: 300px;
  text-align: justify;
}

#jobs_content #jobs_listOfEvents {
    overflow: hidden;
    animation-name: jobs_agendaSlide;
    animation-duration: 25s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    position: relative;
}

#jobs_listOfEvents:hover {
  animation-play-state: paused;
}

@keyframes jobs_agendaSlide {
    from {
        top: 10px;
    }
    
    to {
        top: -200px;
    }
}
    <div id="jobs_container">
    <div id="jobs_header">
      <div id="jobs_header_left">
      </div>
      <div id="jobs_header_center">
        Center text
      </div>
      <div id="jobs_header_right">
      </div>
    </div>
      <div id="jobs_content">
          <div id="jobs_listOfEvents">
            line1<hr>
            line2<hr>
            line3<hr>
            line4<hr>
            line5<hr>
            line6<hr>
            line7<hr>
            line8<hr>
            line9<hr>
          </div>
      </div>
  </div>

GTM Preview Error: JavaScript Compiler Error

I am getting the below error in GTM when I select preview:

enter image description here

I ran my script through JS Lint to make sure there were no errors, additionally I haven’t changed anything to the line / character it is calling out so I’m not entirely sure what the fix is.

Here is a sample of what my script looks like:

function() {
    // Set inputVariable to the input you want to assess
    var inputVariable = {{Page URL}};
    // Set defaultVal to what you want to return if no match is made
    var defaultVal = undefined;
    // Add rows as two-cell Arrays within the Array "table".
    // The first cell contains the RegExp you want to match
    // the inputVariable with, the second cell contains the
    // return value if a match is made. The third cell (optional),
    // contains any RegEx flags you want to use.
    //
    // The return value can be another GTM variable or any
    // supported JavaScript type.
    //
    // Remember, no comma after the last row in the table Array,
    // and remember to double escape reserved characters: \?
    // Row 1 is master, row 2 is staging.  Repeat for every app
    var table = [
//Website Name
      ["URL", "GA4 Lookup Reference Name"],
];  **<----- THIS IS THE LINE THAT IS GIVING ME ISSUES**
    // Go through all the rows in the table, do the tests,
    // and return the return value of the FIRST successful
    // match.
    for (var i = 0, len = table.length; i < len; i += 1) {
        var regex = new RegExp(table[i][0], table[i][2]);
        if (regex.test(inputVariable)) {
            return table[i][1];
        }
    }
    return defaultVal;
}

Any ideas what the fix is here?

I tried correcting the error by adding in an additional ‘,’. I also looked at previous versions which worked and did not see any differences aside from some new URL’s I’ve added in.

Calling on bash file using node.js

I am trying to find a correct script to call on my bash file, which has an authenticated org to login before running my playwright script. I currently am leveraging the codegen tool to generate javascript code from my UI. At the moment all my login credentials are integrated in that script. I have a bash file that can run and automatically login to my org(No credentials needed). The problem I am having is trying to call on the bash before hand to login and then resume running my playwright script. I have checked authentication documentation on Playwright home page but haven’t been successful. Is there a better way of doing this or will calling on the bash file first work?

I tried to run

`’const cp = require (‘child_process’);
const { stdout } = require(‘process’);

cp.exec ('ls -l' , (err, stdout, stderr) => {
console.log('Test')
console.log (stdout);
 });'`

Touchend not allowed to play media element on iOS

According to this article https://webkit.org/blog/6784/new-video-policies-for-ios/ touchend should be able to trigger a play event on iOS. However in the example below a press on the element fires the action and starts the audio playback. A touch drag fires the action but returns a promise rejection and does not start the audio playback. Any idea on how to work around this?

 el.addEventListener("touchend", stb.task.dragEnd );
 el.addEventListener("mousedown", stb.task.dragEnd );

How to play sound when a button is clicked in sync

i am trying to make this clicker game and since you are supposed to click fat the sound i am playing is not in sync

    var music = new Audio('music/vine-boom.mp3');
    function onClick(){
      clicks += 1;
      document.getElementById("clicks").innerHTML = clicks;
      music.play(); 
`    music.currentTime=0;
};```

Return old and new value from comparing function

I have a function that compare two models and return the difference as the following example:

function getPropertyDifferences(obj1, obj2, type) {
    return Object.entries(obj1).reduce((diff, [key, value]) => {
      // Check if the property exists in obj2.
      if (obj2.hasOwnProperty(key)) {
        const val = obj2[key];
  
        if (typeof val === "string") {
          const obj1Date = new Date(value.toString());
          const obj2Date = new Date(val);
          // check if the values are valid dates. if not, we go through regular comparison
          if (!isNaN(Number(obj1Date)) && !isNaN(Number(obj2Date))) {
            return obj1Date.toDateString() !== obj2Date.toDateString() ? { ...diff,
              [key]: val
            } : diff;
          }
        }
       
        if((val === null || undefined) && value === 0){
         return;
        }
  
        // Check if obj1's property's value is different from obj2's.
        if (val !== value) {
          return {
            ...diff,
            [key]: val,
          };
        }
      }
  
      // Otherwise, just return the previous diff object.
      return diff;
    }, {});
  }
  
  const a = {
  dateOfBirth: "Wed Jan 06 2021 12:00:05 GMT-0700 (Mexican Pacific Standard Time)",
  name: "test",
  testValue: "this is the old value",
  testValue2: "value2"
};
const b = {
  dateOfBirth: "2021-01-06T12:00:05.357",
  name: "test",
  testValue: "this is the new one",
  testValue2: "new value2"
};

console.log(getPropertyDifferences(a, b));

Now I have a new model that has the following properties:

export class ProfileActivity {
  oldValue: string;
  newValue: string;
  description: string;
}

So, in the TS I use it as:

profileActivity: ProfileActivity[]

Now, in the function, I want to return this model instead of only the new value in the following format:

[{
    oldValue: oldValueName
    newValue: newValueName
    description: Updated or Deleted(type)
   }],
   [{
    oldValue: oldValueName
    newValue: newValueName
    description: Updated or Deleted(type)
   }]
   ...etc

How can I achieve that?

How would I write a win condition check for a Tic Tac Toe game based on using arrays?

Basically, I wrote a simple tic tac toe game. it uses a 2d array to represent the board (0 being empty, 1 being X and 2 being O)

I checked out solutions by other people but they used a whole different way to represent the board

here is the HTML

let board = [
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
];
//the team symbols
let teamcross = "x";
let teamcircle = "o";
//for the tileclick function
let x = 0;
let y = 0;
var tile = "test";
//1 is Team X and 2 is Team O
var currentteam = 1;
//the tileclick function
function tileclick(tile, y, x) {
  switch (currentteam) {
    case 1:
      document.getElementById(tile).innerHTML = "x";
      board[y][x] = 1;
      console.log(board)
      currentteam = 2;
      document.getElementById("turndisplay").innerHTML = "current team is: O";
      break;
    case 2:
      document.getElementById(tile).innerHTML = "o"
      board[y][x] = 2;
      console.log(board)
      currentteam = 1;
      document.getElementById("turndisplay").innerHTML = "current team is: X";
      break;
    default:
      window.alert("something is broken. Current Team is " + currentteam);
      break;
  }

}
<table id='gameboard'>
  <tr id="toprow">
    <td class="tile" onclick="tileclick('tl',0,0)" id="tl">*</td>
    <td class="tile" onclick="tileclick('tc',0,1)" id="tc">*</td>
    <td class="tile" onclick="tileclick('tr',0,2)" id="tr">*</td>
  </tr>
  <tr id="middlerow">
    <td class="tile" onclick="tileclick('cl',1,0)" id="cl">*</td>
    <td class="tile" onclick="tileclick('cc',1,1)" id="cc">*</td>
    <td class="tile" onclick="tileclick('cr',1,2)" id="cr">*</td>
  </tr>
  <tr id="bottomrow">
    <td class="tile" onclick="tileclick('bl',2,0)" id="bl">*</td>
    <td class="tile" onclick="tileclick('bc',2,1)" id="bc">*</td>
    <td class="tile" onclick="tileclick('br',2,2)" id="br">*</td>
  </tr>

  <h3 id="turndisplay">current team is: X</h3>