I am trying to use an array in my code but I am getting an error message that says pop is not defined. I want to remove the number 50 from the array.
Here is what I tried:
let digits = [5,25,50,100]
let allDigits = digits
allDigits[pop](50)
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I am trying to use an array in my code but I am getting an error message that says pop is not defined. I want to remove the number 50 from the array.
Here is what I tried:
let digits = [5,25,50,100]
let allDigits = digits
allDigits[pop](50)
I want to Upload into GCS using Typescript.
I am using Service Account Json for credentials.
When I tested it it says Uploaded Successfully. But, when I checked the server there was no
file uploaded. Any Idea what this might cause?
import { Storage } from '@google-cloud/storage'
import { SSM } from 'aws-sdk'
import fs from 'fs'
import os from 'os'
export async function uploadFileToGCS(filename: string, bucketName: string): Promise<any> {
// GCSサービスアカウントの認証情報を指定します。
const serviceAccountCredentials = await getParameter()
const credentials = JSON.parse(serviceAccountCredentials)[0]
const projectId = 'my-project-id'
const storage = new Storage({
projectId: projectId,
credentials: credentials,
})
const filePath = os.tmpdir()
// Create CSV
fs.writeFileSync(`${filePath}/${filename}`, '', { encoding: 'utf-8' }) // Write the file to the writable directory
console.log(`CSV file "${filename}" has been created.`)
try {
const bucket = storage.bucket(bucketName)
await bucket.upload(`${filePath}/${filename}`, {
destination: filename,
})
console.log(`File ${filename} uploaded to ${bucketName}.`)
return Promise.resolve({
statusCode: 200,
body: 'Successfully Uploaded',
})
} catch (err) {
console.error('Error uploading file:', err)
return Promise.resolve({
statusCode: 500,
body: 'Failed with Uploading',
})
}
}
I am expecting the file to be uploaded into the server.
Not all elements focus programmatically
function validateAccountPage()
{
var combined_form_array = arrInputFields.concat(arrSelectFields); console.log(combined_form_array);
combined_form_array.forEach(myFunction);
function myFunction(item, index)
{
console.log("Index-"+index+" Item-"+item.id+"n")//lists my fields correctly here
if(document.getElementById(item.id).value==="")
{
document.getElementById(item.id).focus();
}
}
}
Why is county not focusing programmatically
I need to create a selection with native JS or TinyMCE methods.
Currently I have this code that does what is shown in the image below:
const table = editor.dom.getParent(editor.selection.getNode(), 'table');
if (table) {
editor.selection.select(table);
}
I have also tried to do this and it turns out the same as above:
const table = editor.dom.getParent(editor.selection.getNode(), 'table');
if (table) {
const rng = editor.dom.createRng();
rng.selectNode(table);
editor.selection.setRng(rng);
}
I need to make this type of selection with the mouse:
I’m developing a system where a user can add an international address using a web page.
I was looking for a better way to validate an international address and found that Google Wallet has a great approach.
Is there anyway that I can use the same approach for address validation (show relatable address fields for each country) as in Google Wallet using javascript/jquery.
attached is the image and is my expected results. I’d like to add the text Vehicle and Percentage above the legend and also align them legend text and the number. How to do this using Highcharts?
Highcharts.chart("container", {
colors: ["#01BAF2", "#71BF45", "#FAA74B", "#B37CD2"],
chart: {
type: "pie"
},
accessibility: {
point: {
valueSuffix: "%"
}
},
title: {
text: "February 2020 Norway passenger auto registrations"
},
subtitle: {
text:
'Source:<a href="https://cleantechnica.com/2020/03/07/pioneering-norway-rises-above-68-plug-in-vehicle-market-share-in-february/">cleantechnica</a>'
},
tooltip: {
pointFormat: "{series.name}: <b>{point.percentage:.0f}%</b>"
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: "pointer",
dataLabels: {
enabled: true,
formatter: function () {
return this.point.name + ' ' + this.y;
}
},
showInLegend: true
}
},
series: [
{
name: "Registrations",
colorByPoint: true,
innerSize: "75%",
data: [
{
name: "EV",
y: 68.1
},
{
name: "Hybrids",
y: 11.0
},
{
name: "Diesel",
y: 11.2
},
{
name: "Petrol",
y: 9.7
}
]
}
],
legend: {
align: "right",
verticalAlign: "middle",
enabled: true,
itemWidth: 200,
useHTML: true,
labelFormatter: function () {
return this.name + " " + Math.round(this.percentage * 100) / 100 + "%";
}
}
});
I’ve tried using labelFormatter annd legend text but nothing fits my need.
Good evening,
Could someone please assist me and let me know why I am receiving an error for my javascript code?
SyntaxError: Unexpected number (at script.js:15:24) FYI: line 15 on my javascript is the function Person(Harry, 22).
function Person(Harry, 22) {
this.name = Harry;
this.age = 22;
}
console.log(Person);
I was expecting to see his name and age.
I’m using the below call to popupnumericKeypad.html and is working fine in my screen but the problem is the size and position of this popup is not the same from other screens, so can I make my popup adjusting correctly to different screen sizes or resolutions?
window.open(‘UILib/numericKeypad.html?incTime=1&okCall=MSDS_OperatingRoom_UI_OperatingRoom1_setTheatreTimePopup’, ‘numericKeypad’, ‘status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=280,width=240’);
and this is the code in my popup
<html>
<head>
<title>Numeric Keypad</title>
<style type="text/css">
body {
margin: 0px;
padding: 10px;
background-image : url(../images/bkground.gif);
text-align: center;
}
#main {
padding: 0px;
background: #DCE2E8;
width: 180px;
height: 260px;
font-family: Trebuchet MS;
font-size: 0.8em;
}
input.text {
font-family: verdana;
}
</style>
<script language="javascript">
function numClick(val) {
if (val=='C') {
document.Keypad.Quantity.value = '';
} else {
document.Keypad.Quantity.value = document.Keypad.Quantity.value + '' + val;
}
}
function ok() {
// call opener return function
if (incDec != '' || eval(incDec > 0)) {
var quan = document.Keypad.Quantity.value;
// check neg
if (quan.indexOf("-") > -1 && quan.indexOf("-") > 0) {
alert('Not a valid number.');
document.Keypad.Quantity.value = '';
return false;
}
// check decimal
if (quan.indexOf(".") > -1) {
var rest = quan.substring(quan.indexOf(".")+1, quan.length);
if (rest.indexOf(".") > -1) {
alert('Not a valid number.');
document.Keypad.Quantity.value = '';
return false;
}
if (quan.indexOf("-") > -1 && quan.indexOf(".") == 1) {
document.Keypad.Quantity.value = "-0" + quan.substring(quan.indexOf("."), quan.length);
} else if (quan.indexOf(".") == 0) {
document.Keypad.Quantity.value = "0" + document.Keypad.Quantity.value;
}
}
} else if (incTimeSec != '' || eval(incTimeSec > 0)) {
//check time
var timetemp = document.Keypad.Quantity.value;
var s = timetemp.split(":");
if (!s[1]){
var timevar = s[0];
if(timevar.length == 1) {
timevar = '00000' +timevar;
} else if(timevar.length == 2) {
timevar = '0000' + timevar;
} else if(timevar.length == 3) {
timevar = '000' + timevar;
} else if(timevar.length == 4) {
timevar = '00' + timevar;
} else if(timevar.length == 5) {
timevar = '0' + timevar;
}
s[0] = timevar.substr(0,2);
s[1] = timevar.substr(2,2);
s[2] = timevar.substr(4,2);
}
var value = "";
var h = parseInt( s[0], 10);
var m = parseInt( s[1], 10);
var s = parseInt( s[2], 10);
if((h < 24) && (m < 60) && (s < 60)) {
var hrs = "" + h;
var mins = "" + m
var secs = "" + s;
hrs = ((hrs.length==1) ? ('0' + hrs) : hrs);
mins = ((mins.length==1) ? ('0' + mins): mins);
secs = ((secs.length==1) ? ('0' + secs): secs);
value = hrs + ":" + mins + ":" + secs;
}
if (value == "") {
alert('Not a valid time, it must be in the format hh:mm:ss');
document.Keypad.Quantity.value = '';
return false;
}
document.Keypad.Quantity.value = value;
} else if (incTime != '' || eval(incTime > 0)) {
//check time
var timetemp = document.Keypad.Quantity.value;
var s = timetemp.split(":");
if (!s[1]){
var timevar = s[0];
if(timevar.length == 1) {
timevar = '000' +timevar;
} else if(timevar.length == 2) {
timevar = '00' + timevar;
} else if(timevar.length == 3) {
timevar = '0' + timevar;
}
s[0] = timevar.substr(0,2);
s[1] = timevar.substr(2,2);
}
var value = "";
var h = parseInt( s[0], 10);
var m = parseInt( s[1], 10);
if((h < 24) && (m < 60)) {
var hrs = "" + h;
var mins = "" + m
hrs = ((hrs.length==1) ? ('0' + hrs) : hrs);
mins = ((mins.length==1) ? ('0' + mins): mins);
value = hrs + ":" + mins;
}
if (value == "") {
alert('Not a valid time, it must be in the format hh:mm');
document.Keypad.Quantity.value = '';
return false;
}
document.Keypad.Quantity.value = value;
}
returnVal = trim(document.Keypad.Quantity.value);
var okFunc = new Function("window.opener." + okCall + "(returnVal);");
okFunc();
window.close();
}
function cancel() {
if (cancelCall != '') {
var cancelFunc = new Function("window.opener." + cancelCall + "();");
cancelFunc();
}
window.close();
}
function getParam(name) {
var regexS = "[\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var loc = window.location.href;
var results = regex.exec(loc);
if (results == null) return "";
else return results[1];
}
function trim(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function allowOnlyNumeric(){
var key = window.event.keyCode;
if ((key > 47 && key < 58) || key == 46 || key == 45 || key ==58) {
return;
} else {
window.event.returnValue = null;
}
}
// get params
var okCall = getParam('okCall');
var cancelCall = getParam('cancelCall');
var initVal = getParam('initVal');
var incDec = getParam('incDec');
var incTime = getParam('incTime');
var incTimeSec = getParam('incTimeSec');
var incNeg = getParam('incNeg');
</script>
</head>
<body>
<form method="post" name="Keypad">
<div id="main" align="center">
<table cellpadding="0" cellspacing="5" width="170">
<tr>
<td colspan="3" align="center">
<input type="text" id="Quantity" name="Quantity" size="22" tabIndex="1" onkeypress="javascript:allowOnlyNumeric();">
</td>
</tr>
<tr>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(7);" border="0"><img src="../images/7.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(8);" border="0"><img src="../images/8.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(9);" border="0"><img src="../images/9.gif"></a>
</td>
</tr>
<tr>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(4);" border="0"><img src="../images/4.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(5);" border="0"><img src="../images/5.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(6);" border="0"><img src="../images/6.gif"></a>
</td>
</tr>
<tr>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(1);" border="0"><img src="../images/1.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(2);" border="0"><img src="../images/2.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(3);" border="0"><img src="../images/3.gif"></a>
</td>
</tr>
<tr>
<td align="center">
<div id="incDecDiv" style="display:none;">
<a tabIndex="-1" onClick="javascript:numClick('.');" border="0"><img src="../images/Dot.gif"></a>
</div>
<div id="incNegDiv" style="display:none;">
<a tabIndex="-1" onClick="javascript:numClick('-');" border="0"><img src="../images/MathMinus.gif"></a>
</div>
<div id="incTimeDiv" style="display:none;">
<a tabIndex="-1" onClick="javascript:numClick(':');" border="0"><img src="../images/Colon.gif"></a>
</div>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick(0);" border="0"><img src="../images/0.gif"></a>
</td>
<td align="center">
<a tabIndex="-1" onClick="javascript:numClick('C');" border="0"><img src="../images/NumClear.gif"></a>
</td>
</tr>
<tr valign="middle">
<td align="center">
<div id="incNegDiv2" style="display:none;">
<a tabIndex="-1" onClick="javascript:numClick('-');" border="0"><img src="../images/MathMinus.gif"></a>
</div>
</td>
<td align="center">
<a tabIndex="2" onClick="javascript:ok();" onkeypress="javascript:ok();"border="0"><img src="../images/Tick.gif"></a>
</td>
<td align="center" >
<a tabIndex="3" onClick="javascript:cancel();" onkeypress="javascript:cancel();" border="0"><img src="../images/XCancel.gif"></a>
</td>
</tr>
</table>
</div>
</form>
</body>
<script language="javascript">
document.Keypad.Quantity.value = initVal;
document.Keypad.Quantity.focus();
if (document.Keypad.Quantity.value != '') {
document.Keypad.Quantity.select();
}
if (incDec != '' || eval(incDec > 0)) {
var incDecDiv = document.getElementById('incDecDiv');
incDecDiv.style.display = 'inline';
} else if ((incTime != '' || eval(incTime > 0)) || (incTimeSec != '' || eval(incTimeSec > 0))) {
var incTimeDiv = document.getElementById('incTimeDiv');
incTimeDiv.style.display = 'inline';
}
if (incNeg != '' || eval(incNeg > 0)) {
if (document.getElementById('incDecDiv').style.display == 'inline') {
var incNegDiv = document.getElementById('incNegDiv2');
incNegDiv.style.display = 'inline';
} else {
var incNegDiv = document.getElementById('incNegDiv');
incNegDiv.style.display = 'inline';
}
}
</script>
</html>
Thanks
I did try a couple of solution with no luck
my code have two buttons, each button has a value for a specific language, i use google translator for this code, so i copied a function from stackoverflow that turn website into one specific language. the link is given below where from i copy it.
change of language on button click works, and it also works when i change it back to default language, but it does not work when i click on button again to change the language, it shows some other language on google toolbar but it works if i press it once more.
so kindly check this function, that it works good on first click but not on second click, and again works on third click, and so on.
i took a code from (Javascript/Jquery call Google Translate on button click (with flags)) i didnt change the function of it, just add two buttons.
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<p>Hello everybody!</p>
<p>Translate this page.</p>
<!-- hide auto-created selection field completely by hiding it's container -->
<div id="google_translate_element" style="display:none"></div>
<p>You can translate the content of this page by selecting a language in the input field.</p>
<!-- flag: you can choose language here: en, de, af etc. -->
<button value="ur" id="urLanguage"
onclick="changeLanguageToUrduByButtonClick()">Urdu</button>
<button class="notranslate" value="en" id="enLanguage"
onclick="changeLanguageToEngByButtonClick()" style="display:none;">English</button>
</body>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: "en"}, 'google_translate_element');
}
function changeLanguageToUrduByButtonClick() {
var x = document.getElementById("urLanguage");
x.style.display = "none";
var y = document.getElementById("enLanguage");
y.style.display = "block";
var language = document.getElementById("urLanguage").value;
var selectField = document.querySelector("#google_translate_element select");
for(var i=0; i < selectField.children.length; i++){
var option = selectField.children[i];
// find desired langauge and change the former language of the hidden selection-field
if(option.value==language){
selectField.selectedIndex = i;
// trigger change event afterwards to make google-lib translate this side
selectField.dispatchEvent(new Event('change'));
break;
}
}
}
function changeLanguageToEngByButtonClick() {
var x = document.getElementById("enLanguage");
x.style.display = "none";
var y = document.getElementById("urLanguage");
y.style.display = "block";
var language = document.getElementById("enLanguage").value;
var selectField = document.querySelector("#google_translate_element select");
for(var i=0; i < selectField.children.length; i++){
var option = selectField.children[i];
// find desired langauge and change the former language of the hidden selection-field
if(option.value==language){
selectField.selectedIndex = i;
// trigger change event afterwards to make google-lib translate this side
selectField.dispatchEvent(new Event('change'));
break;
}
}
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?
cb=googleTranslateElementInit"></script>
</html>
I’m using React JS, and I’m trying to find the average of this array:
[
"75.0%",
"50.0%",
"66.66666666666666%",
"66.66666666666666%",
"33.33333333333333%",
"58.333333333333336%",
"50.0%",
"66.66666666666666%",
"41.66666666666667%",
"75.0%",
"41.66666666666667%",
"50.0%",
"50.0%",
"72.72727272727273%"
]
Here’s my current code:
const percentCorrects = [
"75.0%",
"50.0%",
"66.66666666666666%",
"66.66666666666666%",
"33.33333333333333%",
"58.333333333333336%",
"50.0%",
"66.66666666666666%",
"41.66666666666667%",
"75.0%",
"41.66666666666667%",
"50.0%",
"50.0%",
"72.72727272727273%"
]
const sum = percentCorrects.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0);
const averaged = sum / percentCorrects.length;
console.log("averaged", averaged);
Right now, my console shows
averaged NaN
Which I looked it up: “The NaN global property is a value representing Not-A-Number”
How do you recommend I fix my code?
I want to be able to display an averaged percentage on my UI, for example: “Average Percent Correct: 48%”
Please let me know how I could fix my code. Thank you
Hello code friends I have an assignment, new to this
Add an event listener to the first button that changes the text within the to EITHER all uppercase or all lowercase, depending on current state.
I need to change all paragraph under h1 to lowercase or uppercase, at the click of a button.
in HTML
I made an id to p.
I made a button with an id
in JS
I used getElementById to bring my button and paragraph.
const textChange = document.getElementById(“btnChange1”);
console.log(textChange);
const txtChange = document.getElementById(“myP”);
textChange.addEventListener(“click”, () => {
}
});
that’s as far as I can get, thanks in advance!
I am building an electron app that requires recording audio and saving it in the directory of my main.js. I got the recording as a blob and then turned it into an array buffer in order to send it to my backend.
In the startRecording function I use the mediarecorder to save the audio and then send it to main
const startRecording = async () => {
console.log('Recording started');
chunks = [];
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
chunks.push(event.data);
};
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: 'audio/wav' });
// Convert Blob to buffer
blob.arrayBuffer().then(buffer => {
// Sending audio data to the main process using the function exposed in the preload script
window.sendAudioToMain.send(buffer);
}).catch(error => {
console.error('Error converting Blob to buffer:', error);
});
const audioUrl = URL.createObjectURL(blob);
const audioElement = document.getElementById('audioElement');
audioElement.src = audioUrl;
};
mediaRecorder.start();
};
ipcMain.on('save-audio', async (event, buffer) => {
try {
// Convert the buffer back into a Blob
const audioBlob = new Blob([buffer], { type: 'audio/wav' });
// Print the MIME type of the blob
console.log('MIME Type:', audioBlob.type);
} catch (error) {
console.error('Error:', error);
}
});
In my code block I have the array buffer turned back into a blob, but what I would really like to know is how I can convert this into a wav file
I am getting below error
Type ‘{ error: false; }’ is not assignable to type ‘x’.
Type ‘{ error: false; }’ is missing the following properties from type ‘ErrorWithMessage2’: name, message
I am trying to add conditional tying error: true then errorMessage is required
else error: false errorMessage is non mandatory
interface Error {
error: boolean;
}
interface ErrorWithMessage extends Error {
error: true;
errorMessage: string;
}
interface ErrorWithMessage2 extends Error {
error: false;
errorMessage?: string;
}
type x = ErrorWithMessage | ErrorWithMessage2;
const abc: x = {
error: false,
};
if you see abc is type “x” still giving error why ?
This is the second time I’m posting this. My previous post was closed without resolving my issue.
This is my question.
Please help me calculate the scrollProgress so that my pathIcon always stays within the screen when scrolling. Or if you have any other ideas, please let me know.
Here is my code :
pathIcon.style.offsetPath = `path('${Path_440.getAttribute("d")}')`;
const pathLength = Path_440.getTotalLength();
function clamp(min, val, max) {
return Math.min(Math.max(min, val), max);
}
function updatePath() {
const docElt = document.documentElement;
const pathBox = theFill.getBoundingClientRect();
// calculates scroll progress based on viewport progress
const scrollProgress = clamp(
0,
-pathBox.y / (pathBox.height - docElt.clientHeight),
1
);
pathIcon.style.offsetDistance = `${scrollProgress * 100}%`;
// These lines fill in the dashes as you scroll down.
const drawLength = pathLength * scrollProgress;
const rest = pathLength - drawLength;
theFill.style.strokeDasharray = `${drawLength}px ${rest}px`;
}
updatePath();
window.addEventListener("scroll", () => updatePath());
body {
height: 500vh;
background: #f1f1f1;
}
.container {
display: flex;
justify-content: center;
}
#pathIcon {
position: absolute;
inset: 0;
width: 100px;
height: 100px;
offset-rotate: 0rad;
}
.middlePath {
position: absolute;
}
.crossLine {
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div style="height: 175px"></div>
<div class="container">
<div style="position: relative">
<img
class="crossLine"
src="/public/pngegg.png"
width="580"
height="1500"
alt=""
/>
<svg
width="540"
height="2990"
viewBox="0 0 540 2990"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="middlePath"
>
<defs>
<path
id="Path_440"
d="M253.744 2C253.744 2 8.36236 68.4995 17.2435 261C26.1246 453.5 380.243 311.5 380.243 531C380.243 750.5 15.2436 631.5 2.24357 826C-10.7564 1020.5 500.798 1091 535.244 1258.5C569.689 1426 296.243 1473 279.744 1460.5"
stroke="#F39029"
stroke-width="4"
/>
</defs>
<use href="#Path_440" stroke-dasharray="20 10" />
<use id="theFill" href="#Path_440" />
</svg>
<svg
id="pathIcon"
viewBox="0 0 100 191"
fill="none"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<rect width="100" height="191" fill="url(#pattern0)" />
<defs>
<pattern
id="pattern0"
patternContentUnits="objectBoundingBox"
width="1"
height="1"
>
<use
xlink:href="#image0_126_965"
transform="matrix(0.00376726 0 0 0.00197239 -0.00104536 0)"
/>
</pattern>
<image
id="image0_126_965"
width="266"
height="507"
xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUh"
/>
</defs>
</svg>
</div>
</div>
</body>
</html>
It looks fine at first glance, but when I scroll, the pathIcon moves too fast and sometimes goes off-screen. I want it to slow down or stay fixed in the middle of the screen but still move to the path. This would make it smoother and give a better overview of the path.
Here is the current state and my desired outcome.
Please help me. Thank you for all your responses
I’ve tried the method mentioned above, but it still doesn’t keep the pathIcon within the screen when scrolling. The pathIcon moves too fast and goes off-screen.
When I run build on local I get no errors, but in Vercel I get this error:
Error occurred prerendering page "/pt/my-profile".
TypeError: Cannot read properties of undefined (reading '0')
It only happens in this page.tsx:
"use client";
import Text from "@/app/components/Text";
import {
Button,
Card,
CardBody,
Link,
Snippet,
Avatar,
} from "@nextui-org/react";
import { IconPencil, IconTrash } from "@tabler/icons-react";
import { useUserContext } from "@/app/context/UserContext";
import { getCountry } from "@/app/utils/getCountry";
import { useTranslations } from "next-intl";
import PillPalIcon from "./components/PillPalIcon";
import HealthSyncIcon from "./components/HealthSyncIcon";
const MyProfilePage = ({
params: { locale },
}: {
params: { locale: string };
}) => {
const { user } = useUserContext();
const country = getCountry();
const t = useTranslations("myProfile");
const details: string[][] = [
[
t("personalInfo.name"),
t("personalInfo.age"),
t("personalInfo.gender"),
t("personalInfo.country"),
t("personalInfo.language"),
],
[user?.name, user?.age, user?.gender, country, locale],
];
return (
<main className="min-h-screen flex flex-wrap justify-evenly p-12">
<section className="flex flex-col [&>*]:p-10 [&>*]:my-4">
<Card>
<Text>
{t("title")}: {user.profileType}
</Text>
<CardBody className="flex flex-row items-center">
<Avatar name={""} size="lg" className="m-2" />
<div className="[&>*]:m-2 flex flex-col">
<Button
radius="full"
variant="solid"
color="primary"
endContent={<IconPencil />}
>
{t("btns.change")}
</Button>
<Button
radius="full"
variant="bordered"
endContent={<IconTrash />}
>
{t("btns.remove")}
</Button>
</div>
</CardBody>
</Card>
<Card>
<Text> {t("personalInfo.title")}</Text>
<CardBody className="flex flex-row justify-between">
{details?.map((detail, i) => (
<div
key={i}
style={{
fontWeight: i === 0 ? "bold" : "normal",
}}
className="flex flex-col font-black [&>*]:m-2"
>
{detail?.map((item, j) => (
<p key={j}>{item}</p>
))}
</div>
))}
</CardBody>
</Card>
<Card>
<Text>{t("conditions.title")}</Text>
<CardBody className="[&>*]:m-2">
{user?.existingHealthCondition &&
user?.existingHealthCondition.map(
(condition: string, i: number) => (
<Snippet
hideCopyButton
hideSymbol
key={i}
className="grid place-content-center"
>
{condition}
</Snippet>
)
)}
</CardBody>
</Card>
</section>
<section className="flex flex-col [&>*]:p-10 [&>*]:my-4">
<Card>
<Text>{t("sync.title")}</Text>
<p>{t("sync.description")}</p>
<CardBody className="flex flex-row justify-between">
<div className="flex flex-col [&>*]:m-2">
<p className="flex items-center [&>*]:mr-2">
<PillPalIcon />
PillPal
</p>
<p className="flex items-center [&>*]:mr-2">
<HealthSyncIcon />
HealthSync
</p>
</div>
<div className="flex flex-col [&>*]:m-2">
<Link className="text-[#63A87D]">{t("sync.pillpal")}</Link>
<Link className="text-[#63A87D]">{t("sync.healthsync")}</Link>
</div>
</CardBody>
</Card>
</section>
</main>
);
};
export default MyProfilePage;
Its a profile page with nothing particular, fairly static… It works perfectly in local.
Im using next": "14.0.2"
This is my next.config.json
:
const createNextIntlPlugin = require("next-intl/plugin");
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
eslint: {
ignoreDuringBuilds: true,
},
compiler: {},
images: {
unoptimized: true,
remotePatterns: [
{
protocol: "https",
hostname: "d1pe6f90ru47yo.cloudfront.net",
},
],
},
};
module.exports = withNextIntl(nextConfig);
I’ve tried to downgrade and upgrade some versions many times… But nothing seems to be working. And The only info I get from Vercel is that line TypeError: Cannot read properties of undefined (reading '0')
Which is false, because If I Comment all the code of the page I still get the error…
Pls can someone help me?