Error with Next 13 async Component Data fetching

i’m using Nextjs 13 and this is my component:

"use client";

import { Carousel } from "react-responsive-carousel";
import Image from "next/image";
import axios from "axios";
import { useState } from "react";
import Product from "./product";

export default function Page() {
  return (
    <div className="container">
      <div className="searchComponent">
        <input type="text" placeholder="Search" />
        <button>
          <i className="icon-search"></i>
        </button>
      </div>
      <Carousel showThumbs={false}>
        <div>
          <Image
            src={"/assets/slide1.png"}
            width="0"
            height="0"
            sizes="100vw"
            style={{ width: "100%", height: "auto" }}
          />
        </div>
        <div>
          <Image
            src={"/assets/slide1.png"}
            width="0"
            height="0"
            sizes="100vw"
            style={{ width: "100%", height: "auto" }}
          />
        </div>
        <div>
          <Image
            src={"/assets/slide1.png"}
            width="0"
            height="0"
            sizes="100vw"
            style={{ width: "100%", height: "auto" }}
          />
        </div>
      </Carousel>
      {/* @ts-expect-error Async Server Component */}
      <Product />
    </div>
  );
}

and this is my Product component:

import React from "react";

async function getData() {
  const res = await axios
    .get(`https://jsonplaceholder.typicode.com/users`)
    .then((res) => {
      return res;
    });
  return res;
}

export default async function Product() {
  const name = await getData();

  return <div>1</div>;
}

but its not working and i getting Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead error.

I also tried but this code {/* @ts-expect-error Async Server Component */} but this problem is still persistent

Mongoose removes callback functions for “Item.insertMany()” and “Item.find()” methods. Can I use these methods in place of the removed methods?

I’m practicing building a todolist app and after discovering that callback functions can no longer be used for Items.insertMany() and Item.find() methods, I discovered an alternative. However, I want to know what might be wrong with this code when I have to insert records and **display **them also on the page.

in other words, I want to insert records into the database, then find them and display them on the page.

app.get("/", function(req, res) {
  Item.find().then(function(){

  if (defaultItems.length === 0){
    Item.insertMany(defaultItems).then(function(){
        console.log("Added successfully!");
      }).catch(function(err){
        console.log(err);
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: "Today", newListItems: defaultItems});
    }
  }).catch(function(err){
    console.log(err);
  })
  });

What could be wrong with this code? I have not seen an error yet but I just used imagination to make it up following the alternatives I read, about the mentioned method calls.

Below is the code from the ejs file

  <div class="box" id="heading">
    <h1> <%= listTitle %> </h1>
  </div>

  <div class="box">

<% newListItems.forEach(function(item){ %>
  <div class="item">
    <input type="checkbox">
  <p> <%= item.name %> </p>
  </div>
<% }); %>


<form class="item" action="/" method="post">
        <input type="text" name="newItem" placeholder="New Item" autocomplete="off">
        <button type="submit" name="list">+</button>
      </form>
  </div>

How to use a function to define the headerShown option of screenOption property of a react native navigator

I am trying to use a function to set the headerShown option to true or false like below:

screenOptions={({ route }) => ({
      headerShown: () => {
        if(route.name !== 'Home'){
          return false;
        }
        return true;
      }
})}

The arrow function above doesn’t seem to fit the expected syntax as it get flagged as unexpected type error.

What has worked:

screenOptions={({ route }) => ({
      headerShown: route.name !== 'Home' ? false : true
})}

Is there a way to use the arrow function so I do more with it?

how to redirect to a local webpage after checking a condition in javascript?

I am trying to check if the details entered by the user are correct or not. If it is correct the user should be redirected to a local login page.
I have tried it again and again but somehow if the user credentials are valid then it doesn’t goto the local html page.

<script>
    let c=1;
    function validate(email, mobno, password) {
        if (validateEmail(email) && validateMobno(mobno) && validatePsswrd(password)) {
            alert("valid");
        }
        else {
            alert("Invalid Details");
            console.log("invalid");
            c=0;
        }
    };
    
    function redir() {
        if (c==1) {
            console.log("redirecting");
            window.location.href = "supplogin.html";    
        }
        else{
            console.log("cancel");
        }
    }
    function validateEmail(email) {
        let mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
        if (email.value.match(mailformat)) {
            return true;
        }
        else {
            return false;
        }
    };
    function validateMobno(mobno) {
        let phno = /^d{10}$/;
        if (mobno.value.match(phno)) {
            return true;
        }
        else {
            return false;
        }
    }
    function validatePsswrd(password) {
        let psswrd = /^[A-Za-z]w{7,14}$/;
        if (password.value.match(psswrd)) {
            return true;
        }
        else {
            return false;
        }
    }
    </script>

I want this to check user details and then redirect to the local page.

PixiJS viewport bounce box not centered

I am using pixi-viewport in vue 3.
I got the bounce box to work and I’ve set it up like so:

viewport.bounce({
          friction: .1,
          bounceBox: new Rectangle(0, 0,
              window.innerWidth,
              window.innerHeight)
        })

But when the image crosses the boundries it bounces back, but not to the center of the screen.
How can I achieve that? I want it to either the center of the screen or the top left.

Thanks in advance.

(Sorry for low frame rate, file was too big)

https://user-images.githubusercontent.com/123364387/225952814-75692ab1-c14f-4a3e-87c8-5dd56fe97a4a.gif

TypeError: Cannot set properties of undefined (setting ‘name’) in Javascript, when the variable should have a value

I am in the midst of creating a recursive function for Get Object.getOwnPropertyDescriptors() from Javascript recursively, and flatten it .

This is the code:

let master = [];
function something (obj,str) {
    
    if (Object(obj)===obj) {
        pobj = Object.getOwnPropertyDescriptors(obj)
        for (let kk in pobj) {
            maststr = str;
        //console.log(obj);
        //console.log("line 8");
        //console.log(kk);
        if (master.includes(kk)||kk==="constructor"||kk==="globalThis"||kk==="global") { //circular reference // ||typeof obj[kk]==="function"
            return;
        } else {
            maststr = str + "." + kk ;
            console.log("line - 1st");
            console.log(maststr);
            console.log(kk);
            console.log(pobj[kk]);
            pobj[kk]["name"] = maststr;
            master.push(pobj[kk]);
            console.log("line - 2nd");
            console.log(maststr);
            if (maststr==="globalThis.Function.prototype.arguments"||maststr==="globalThis.Function.prototype.caller"
                ||maststr==="globalThis.Function.prototype.callee") continue;
            something(obj[kk], maststr);
        }
        
        }
    } else {
        //master.push(obj);
        return;
    }


    }


something(globalThis,"globalThis");
console.log(master);

It worked well until I reached the Object.assign property, which strangely became undefined, and threw the following error:

/Users/user/Documents/playground/playgroundtests_js/E16_2.js:19
            pobj[kk]["name"] = maststr;
                             ^

TypeError: Cannot set properties of undefined (setting 'name')
    at something (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:19:21)
    at something (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:25:4)
    at Object.<anonymous> (/Users/user/Documents/playground/playgroundtests_js/E16_2.js:38:1)
    at Module._compile (node:internal/modules/cjs/loader:1191:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1245:10)
    at Module.load (node:internal/modules/cjs/loader:1069:32)
    at Function.Module._load (node:internal/modules/cjs/loader:904:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:22:47

Indeed, when I console.log this property just before the error was thrown, it was undefined. But when I tested Object.getOwnPropertyDescriptors(Object.assign) on the node REPL, this returned an object.

Why is this so, and how do I solve this?

How to get array values from another page object in Protractor?

I am new to protractor and I’m struggling to get the array values from the "solutions.js", so that I can use the function in "tools.js" to check that the values from "main.js" are expected.

I’m not quite sure how to write it so that I can pass the array values (in idArray1) and also reuse verifyID again but with a different array (with idArray2) as well.

Thank you

Page object 1 (main.js)

var tools = require("./tools.js");
it("ID Contains", async () => {
    ...
    tools.verifyID();
    ...
}

Page object 2 (tools.js)

var tools = require("./solutions.js");
module.exports = {verifyID: verifyID};

function verifyID () {
for (var i = 0; i < checker.length; i++) {
     expect(checkLists).toContain(idArray[i]);
    }
}

Page object 3 (solutions.js)

var idArray1 = ["1005","1015","1025","1035",];
var idArray2 = ["1004","1014","1024","1034",];

Solution For Avoiding For Loop in Current For Loop using JavaScript Objects Here

Here I have 3 arrays,
orderdIds: It contains all ordersIds
associatedUsers: It contains all asscoaited user to the orders.
users: It contains all user details.

Now I have to SET users data into the associatedUsers variable. So how I can do that in a single loop. Here I try with multiple loops below

const orderIds = [101, 102];
const associatedUsers = [{ orderId: 101, userIds: [1, 2] }, { orderId: 102, userIds: [2] }];
const users = [{ userId: 1, email: 'email1' }, { userId: 2, email: 'email2' }];

associatedUsers.map((user) => {
    user.userIds.map((u, index) => {
        const userIndex = users.findIndex((use) => { return u === use.userId; });
        console.log(userIndex)
        if (userIndex > -1) {
            user.userIds[index] = users[userIndex]
        }
    })
});

console.log(associatedUsers);

localstorage value is null

Complete javascript beginner here.

I’m trying to make it so my text document saves its content in my textbox whenever I refresh the page, but for some reason whenever I try to see if the content’s been saved the value just comes back as null.

Here’s my HTML

div class="scratchpad" contenteditable="true" name="scratchpad" id="scratchpad"></div>

and here’s my javascript

let scratchpad = document.querySelector("#scratchpad")

scratchpad.value = localStorage.getItem("notes")

scratchpad.addEventListener("keyup", event => {
    localStorage.setItem("notes", scratchpad.value)
})

I’m using Visual Studio Code in Windows 11

The only thing I can think of is it might have something to do with using contenteditable instead of a textarea but I’m not sure how that would effect the localstorage value.

Any help would be appreciated. And feel free to talk to me like I’m five years old because part of me still can’t wrap my head around some of this stuff.

How to positioning MUI Tooltip at the value mark of the progress bar?

I am creating a progress bar component using the MUI as a foundation. I have tried positioning the Tooltip at the value mark of the progress bar. However, it doesn’t seem to work it always appears in the middle. Is there any way to display the Tooltip dynamically based on the progress bar’s value?

Plus, this is what it should look like, but I can only achieve having a tooltip in the middle. enter image description here

this is how much I am able to achieve.enter image description here

These are the code that I have so far. I did a lot of research, but nobody combined Mui Tooltip and Progress bar. So, I am struggling rn.

import { ReactNode, useEffect useState } from 'react'
import MuiLinearProgress, { LinearProgressProps } from '@mui/material/LinearProgress'
import { Box, Tooltip, Typography } from '@mui/material'

type OmitLinear = Omit<LinearProgressProps, 'variant' | 'color'>

interface LinearProps extends OmitLinear {
  variant?: 'circular' | 'linear' | undefined
  color?: string | undefined
  label?: 'end' | 'under' | 'tooltip' | 'arrowTooltip' | undefined
}

type Props = LinearProps

export const Progress = (props: Props) => {
  const [progress, setProgress] = useState(0)
  const {
   variant = 'linear',
   value = progress,
   color,
   size,
   caption,
   captionColor,
   label
  } = props
  const { classes } = useStyles({ color, size, captionColor, label })

  useEffect(() => {
    const timer = setInterval(() => {
    setProgress((prevProgress) =>
      (prevProgress >= 100 ?
        0
        :
        prevProgress + 1)
      )
    }, 800)
    return () => {
      clearInterval(timer)
    }
  }, [])

  return (
      {(variant === 'circular') ?
        (
          // MuiCircular Progress, this one doesn't need Tooltip
        )
        :
        (
          <Box className={classes.boxLinear}>
            <Box className={classes.boxMuiLinear}>
              {(label === 'tooltip' || label === 'arrowTooltip') ? (
                <Tooltip
                  title={`${Math.round(value)}%`}
                  open={true}
                  placement="top"
                  arrow={(label === 'arrowTooltip') ? true : false}
                >
                  <MuiLinearProgress
                    {...props}
                    variant='determinate'
                    color={undefined}
                    value={value}
                    className={classes.rootLinearProgress}
                  />
                </Tooltip>
              ) : (
                <MuiLinearProgress
                  {...props}
                  variant='determinate'
                  color={undefined}
                  value={value}
                  className={classes.rootLinearProgress}
                />
              )}
            </Box>
            {(label === 'end' || label === 'under') ? (
              <Box className={classes.labelBox}>
                <Typography
                  variant="body2"
                  color="text.secondary">
                  {`${Math.round(value)}%`}
                </Typography>
              </Box>
            )
              : null}
          </Box>
        )
      }
  )
}

I’m trying to make a countdown timer but the time won’t post to my html correctly, what can I do to make this work?



var minutesLeft = 0;
    var secondsLeft = 59;
    var startMazeBtn = document.getElementById("startMazeBtn");
    var setTimer;

   
  // custom entry point for timer star
    entryPoint();
  }
  //timer function

  function entryPoint () {
    handleTimer();
  }

  function startTimer () {
    console.log("startTimerFired");
    var min = minutesLeft;
    var sec = secondsLeft;
    if (sec >= 0) {
      $("#startTimer").text("00:" + (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec));
      sec --;  
    } else if (min >= 0) {
        min - 60;
        sec + 59;
    } else {
      startTimer == 0;
    }
  }

  function handleTimer () {
    //setTimer = setInterval(() => startTimer, 1000);
    setTimer = setInterval(function() {
      startTimer();
      if(startTimer <= 0) {
      clearInterval(setTimer);
      }
    },1000);
  }

    //This is called in the html
    <h3 class="startTimer" id="startTimer">00:00:00</h3>

I’ve tried changing the variables and attempted to log them but it always just runs the interval continually and doesn’t display anything but 00:00:00. I’m trying to get it to that whatever I enter in the variables at the top of the js gets grabbed and processed