Cyclic.sh fails to deploy website, Failed to run “npm run start”

I’m learning front-end and I have to deploy a website that I made using vite react. Everything is fine in my pc, the website loads fine when I do npm run dev, but when I try to deploy it in cyclic.sh or in github it never works… I’ve been dealing with this problem for months, I’ve tried a lot of solutions that I found online but nothing works, please help me

This is my package.json:

{
  "name": "projeto",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "start": "vite",
    "build": "vite build",
    "dev": "vite",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "deploy": "vite build"
  },
  "dependencies": {
    "vite": "^5.0.11",
    "@flaticon/flaticon-uicons": "^3.0.0",
    "@react-google-maps/api": "^2.19.2",
    "body-parser": "^1.20.2",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "nodemailer": "^6.9.7",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.18.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "@vitejs/plugin-react": "^4.0.3",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "vite": "^5.0.11"
  },
  "description": "This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.",
  "main": "vite.config.js",
  "keywords": [],
  "author": "",
  "license": "ISC"
}

This is my vite.config.js

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

console.log('Vite is starting...');

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets', 
    emptyOutDir: true, 
    rollupOptions: {
      input: {
        main: 'src/main.jsx',
      },
    },
  },
});

I’ve tried to change the start command in package.json, changed some stuff in my vite.config.js, but it keeps having the same error

Tooltip on legend with amcharts4

I’m using Angular 16 and amcharts 4.
This is what I need to achieve:

enter image description here

and this is what I’m right now:

enter image description here

How can I add that tooltip to display something I have stored in variables?
This is my actual chart configuration:

    let chart = am4core.create(this.chartId, am4charts.PieChart);
    if (this.useAnimation) am4core.useTheme(am4themes_animated);

    // Add data
    chart.data = this.data;

    // Set inner radius
    chart.innerRadius = am4core.percent(this.innerRadius);

    // Add and configure Series
    let pieSeries = chart.series.push(new am4charts.PieSeries());
    pieSeries.dataFields.value = "score";
    pieSeries.dataFields.category = "type";
    pieSeries.slices.template.stroke = am4core.color(this.borderColor);
    pieSeries.slices.template.strokeWidth = 2;
    pieSeries.slices.template.strokeOpacity = 1;
    pieSeries.slices.template.propertyFields.fill = "color";
    pieSeries.labels.template.disabled = this.labelDisabled;
    pieSeries.ticks.template.disabled = this.tickDisabled;
    if (this.disableTooltipOnHover) pieSeries.slices.template.tooltipText = "";
    if (this.displayLegend) {
      chart.legend = new am4charts.Legend();

      // TODO tooltip not working
      // chart.legend.tooltip = new am4core.Tooltip();
      // chart.legend.tooltip.label.text = "prova tooltip";
      // chart.legend.tooltipPosition = "pointer";
      // console.log(chart.legend.tooltip);
      chart.legend.valueLabels.template.text = this.legendTemplate;
    }
    let hs = pieSeries.slices.template.states.getKey("hover");
    if (!this.sliceOnHover) {
      hs!.properties.scale = 1;
    } else {
      hs!.properties.scale = this.sliceScale;
    }

    // This creates initial animation
    pieSeries.hiddenState.properties.opacity = 1;
    pieSeries.hiddenState.properties.endAngle = -90;
    pieSeries.hiddenState.properties.startAngle = -90;

    let label = chart.seriesContainer.createChild(am4core.Label);
    label.text = this.innerText;
    label.horizontalCenter = "middle";
    label.verticalCenter = "middle";
    label.fontSize = 20;
    // TODO center text 20 NPS

Any idea? In //TODO there is what I tried to add the tooltip, but failing.

Another issue I’m having, it’s about the text inside the circle of the donut chart. I need to write: 20 NPS, on two lines, and I had to add the text like “20 nNPS” to make it work, but I’m not able to center the text as shown in this picture:
enter image description here

What topics should be focused when learning JavaScript for the field of front-end development?

I just started learning JavaScript so I was curious about what things to focus on, as I don’t want to waste time on the things that can be used for back-end development using JavaScript because I just want myself to be equipped with front-end only for now!!

I am trying a course for JavaScript but it is for whole JavaScript language, so I want to know about what can be more beneficial ?

CORS error when trying to fetch an API with API key

I’m trying to fetch an API with an API Key in my nextJS project but It does not read my Key I believe and it also shows me this CORS error:”Access to fetch at ‘https://fleetapi-pt.cartrack.com/rest/’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.” I don’t know how to solve it I do not have access to the server where the api is. MY FETCH IS SOMETHING LIKE THIS I TOOK THE APIKEY OFF CUZ I DONT WANT TO EXPOSE IT ON THE INTERNET


const apiUrl = 'https://fleetapi-pt.cartrack.com/rest/vehicles';

// API key for authentication
const apiKey = 'my_api_key';

let result;

// Make a GET request with authentication using the Fetch API
fetch(apiUrl, {
    headers: {
        Authorization: `Bearer ${apiKey}`,
    },
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(protectedData => {
    result = protectedData;
    console.log('Protected Data:', protectedData);
  })
  .catch(error => {
    console.error('Error:', error);`your text`
  });

GET/POST vs USE in ExpressJS for filtering URL

router.get(‘/’,(req,res,next)=>{
console.log(‘first middleware function’+req.originalUrl)

})

VS

router.use(‘/’,(req,res,next)=>{
console.log(‘first middleware function’+req.originalUrl)

})

Can anyone please help me when i use USE in second code if i put any url after / like ‘/jhds’ so that middleware function runs but when i use GET in first code and put any url after / again like ‘/jhsd’ it doesnt run, so how filtering works in use and get/post?

Implementing Watermark Image Downloads in Next.js: Code Query

This Next.js code enables users to download watermarked images for an improved visual experience on the website. While there’s a current issue where downloaded images may not visibly display the watermark, the code ensures the watermark is retained. The visibility problem is acknowledged and requires further attention. Despite this, users receive images with the watermark intact. The code is tailored for Next.js, simplifying watermarked image downloads on the site

         const handleImageGenerated = (imageData: any) => {
    setDownloadedImage(imageData);
  };
  const downloadImage = () => {
    if (downloadedImage) {
      const a = document.createElement("a");
      a.href = `data:image/jpeg;base64,${downloadedImage}`;
      a.download = "adicto.jpg";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  };

 
  useEffect(() => {
    // Check if downloadedImage is defined before triggering download
    if (downloadedImage !== undefined) {
      downloadImage();
    }
  }, [downloadedImage]);
      <Stack
                      className="container"
                      w={`${
                        props.responseDataImages?.[
                          props.latestGeneratedImagesIndex != null
                            ? props.latestGeneratedImagesIndex
                            : props.responseDataImages.length - 1
                        ].latestImagesdata.width
                      }`}
                      h={`${
                        props.responseDataImages?.[
                          props.latestGeneratedImagesIndex != null
                            ? props.latestGeneratedImagesIndex
                            : props.responseDataImages.length - 1
                        ].latestImagesdata.height
                      }`}
                      maxH={"500px"}
                      pos={"relative"}
                      background="rgba(25, 19, 36, 0.70)"
                      borderRadius={"10px"}
                    >
                      <Watermark
                        height={32}
                        width={165}
                        image="https://uiwjs.github.io/react-watermark/watermark-example.svg"
                      >
                        <Image
                          className="image"
                          src={`data:image/jpeg;base64,${images.imgSrc}`}
                          objectFit={"cover"}
                          borderRadius={"10px"}
                          mx={"auto"}
                          w={`${
                            props.responseDataImages?.[
                              props.latestGeneratedImagesIndex != null
                                ? props.latestGeneratedImagesIndex
                                : props.responseDataImages.length - 1
                            ].latestImagesdata.width
                          }`}
                          h={`${
                            props.responseDataImages?.[
                              props.latestGeneratedImagesIndex != null
                                ? props.latestGeneratedImagesIndex
                                : props.responseDataImages.length - 1
                            ].latestImagesdata.height
                          }`}
                          maxH={"500px"}
                          alt="generated image"
                        />
                      </Watermark>
                      <Box className="middle" w={"100%"} height={"100%"}>
                        <Flex
                          transition="opacity 0.3s ease-in-out"
                          pos={"absolute"}
                          bottom={"15px"}
                          left={"15px"}
                        >
                          <Menu>
                            <MenuButton
                              px={0}
                              bg={"none"}
                              _hover={{
                                bg: "none",
                              }}
                              _active={{
                                bg: "none",
                              }}
                              border={"1px solid rgba(112, 112, 112, 0.2)"}
                              color={"white"}
                              as={Button}
                            >
                              <Flex align={"center"} justify={"center"}>
                                <Image
                                  objectFit={"cover"}
                                  src={AllImages.magicEdit.src}
                                  alt="magic"
                                />
                              </Flex>
                            </MenuButton>
                            <MenuList
                              className="aspectRatio-background"
                              backdropFilter={"blur(50px) brightness(4)"}
                              border={"0.2px solid rgba(112, 112, 112, 0.2)"}
                              color={"white"}
                              fontSize={"12px"}
                              fontFamily={"poppins"}
                              fontWeight={500}
                            >
                              <MenuItem
                                bg={"none"}
                                onClick={() =>
                                  props.handleUpscale(
                                    images.imgSrc,
                                    "latest Images",
                                    index
                                  )
                                }
                              >
                                Upscale
                              </MenuItem>
                              <MenuItem
                                bg={"none"}
                                onClick={() =>
                                  props.ClarifyHandsInImage(
                                    "latest Images",
                                    index,
                                    images.infoSeedValue
                                  )
                                }
                              >
                                Hand Restore
                              </MenuItem>
                              <MenuItem
                                bg={"none"}
                                onClick={() =>
                                  props.faceStore(
                                    "latest Images",
                                    index,
                                    images.infoSeedValue
                                  )
                                }
                              >
                                Face Restore
                              </MenuItem>
                            </MenuList>
                          </Menu>
                        </Flex>
                        <Button
                          bg={"none"}
                          _hover={{
                            bg: "none",
                          }}
                          _active={{
                            bg: "none",
                          }}
                          border={"1px solid rgba(112, 112, 112, 0.2)"}
                          pos={"absolute"}
                          top={"15px"}
                          right={"15px"}
                          px={0}
                          color={"white"}
                          onClick={() => {
                            // Check if watermark is present
                            const watermark =
                              document.querySelector(".watermark");
                            const image = document.querySelector(".image");

                          
                            if (watermark && image) {
                              const clonedImage = new Image();
                              clonedImage.src = image.src;
                              // Remove the watermark from the cloned image
                              clonedImage.onload = () => {
                                const canvas = document.createElement("canvas");
                                canvas.width = clonedImage.width;
                                canvas.height = clonedImage.height;
                                const ctx = canvas.getContext("2d");
                                ctx?.drawImage(clonedImage, 0, 0);
                                ctx?.drawImage(
                                  watermark as HTMLImageElement,
                                  0,
                                  0
                                );
                                const newImageUrl = canvas.toDataURL();
                               
                                props.onImageGenerated(newImageUrl);
                              };
                            } else {
                             
                              props.onImageGenerated(images.imgSrc);
                            }
                          }}
                        >
                          <Flex align={"center"}>
                            
                            <Image
                              objectFit={"cover"}
                              src={AllImages.downloadHd.src}
                              alt="download"
                            />
                          </Flex>
                        </Button>
                      </Box>
                    </Stack>

same code work on localhost but doesnot when hosted [closed]

I am usingxmlHttpRequest to send form data to server.It works when running on localhost but doesnot return the formdata value when hosted on server:

<?php $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $comment = $_POST['comment'];
    echo "Name: " . $name . "<br>";
    echo "Email: " . $email . "<br>";
    echo "Subject: " . $subject . "<br>";
    echo "Comment: " . $comment;
?>

script

 let form = document.myform;
    
    try {
      form.addEventListener("submit", function (e) {
        e.preventDefault();
        let comment = document.getElementById("comment").value;
        let formData = new FormData(form);
    
        if (comment.length != 0 && comment.trim().length != 0) {
          let xmlhttp = new XMLHttpRequest();
    
          xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4) {
              // Check the status code
              if (xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
              } else {
                console.error("HTTP request failed with status:", xmlhttp.status);
              }
            }
          };
    
          xmlhttp.open("POST", "server.php", true);
          xmlhttp.send(formData);
        }
      });
    } catch (e) {
      console.error("Error:", e);
    }

json-server GET /posts?title_like=server not working

this is my json-object

{
  "products": [
    {
      "id": 10001,
      "name": "Basics To Advanced In React",
      "overview": "SOMETHING",
      "long_description": "SOMETHING",
      "rating": 5,
      "in_stock": true,
    },
    {
      "id": 10002,
      "name": "Django Framework for Beginners",
      "overview": "SOMETHING",
      "long_description": "SOMETHING",
      "rating": 5,
      "in_stock": false,
    },
  ],
}

other query’s are working such as given below

http://localhost:8000/products [ works ]
http://localhost:8000/products?id=10001 [ works ]

but these 2 below are not working.

http://localhost:8000/products?name_like=react [ doesnt work ]
http://localhost:8000/products?in_stock=true [ doesnt work ]

this is the API call,

useEffect(() => {
    async function fetchProducts() {
      const response = await fetch(
        `http://localhost:8000/products?name_like=${searchTerm}` // if searchTerm = react
      );

      const data = await response.json();
      setProducts(data);
    }
    fetchProducts();
  }, [searchTerm]);

consol.log(documents) – logs an empty array [] where as i should be getting this object when calling
http://localhost:8000/products?name_like=react

{
  "id": 10001,
  "name": "Basics To Advanced In React",
  "overview": "SOMETHING",
  "long_description": "SOMETHING",
  "rating": 5,
  "in_stock": true,
},

Date Rendering Problem on Front-end with Different Time Zones

I am facing a problem in rendering dates within my web app of a bank when there are differences in time zones. The backend provides the dates in the correct format, but during the rendering on the front end, discrepancies are found, especially when the time zone is different from that of Rome (UTC+2).

Details:

I use React for my web app.
Dates are provided by the backend in the UTC format: “2021-04-01T00:00:00.000+02:00”.
I implemented the dateformat function using the Moment.js library to format dates.
I have noticed that the problem arises when the time difference is more than two hours compared to Rome.

Code:

export const placeholderForNullOrUndefined = '-';

export const dateFormat = (value?: any) => {
  console.log('Real value:', value)
  if (!value) {
    return placeholderForNullOrUndefined;
  }

  const DATE_FORMAT = "DD/MM/YYYY";

  if (!(value instanceof Date)) {
    return moment(value).format(DATE_FORMAT);
  }

  console.log('value', value);

  const data = value;
  const stringDate = value;
  const momentValue = moment(stringDate);
  const timezone = data.getTimezoneOffset() / 60;
  console.log('timezone', timezone);

  return momentValue.utc(true).format(DATE_FORMAT);
};

Additional Questions:

How can I ensure that dates are rendered correctly regardless of time zone?
Are there any adjustments I can make to the dateformat function to better handle differences in time zones?
Thank you so much for your help!

I expect the dates to be equal
both front and back end

How to fix cursor typewriter Jump to end Issue during convert number in JavaScript?

following these questions {What’s the solution and the right way to convert digits in JavaScript?} and {How to convert numbers in JavaScript, and problems with commands to remove non-numeric characters on a keyboard with Tel input} I want to express one of the other problems.

there are not any differences in which method for converting numbers, however in all methods, I have a little problem with this.

my problem is the keyboard typewriter pointer jumps to the end if select a number in the middle of numbers with the mouse or touch (on mobile) and change One or more numbers. please see this image pasted in below for clarification Also add a JSFiddle link.

enter image description here

https://jsfiddle.net/paulvek/4js965fr/7/

const phoneNumberInput = document.getElementById('phoneNumberInput');
phoneNumberInput.addEventListener('input', (event) => {
  const phoneNumberValue = event.target.value;
  const englishPhoneNumberValue = toEnglishDigits(phoneNumberValue);
  const numericPhoneValue = englishPhoneNumberValue.replace(/[^d۰-۹٠-٩]/g, ''); // Added line
  event.target.value = numericPhoneValue;
});

function toEnglishDigits(str) {
  const persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"];
  const arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"];
  const englishNumbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];

  return str.split("").map(c => englishNumbers[persianNumbers.indexOf(c)] ||
    englishNumbers[arabicNumbers.indexOf(c)] || c).join("")
}
<input type="tel" id="phoneNumberInput" />

If the user selects one of the middle digits with the English keyboard and changes it, it will change there and the blinking type indicator of the same type pointer will stay there.

But if he selects and changes one of the middle digits with the Persian or Arabic keyboard, the change is done correctly. But the problem is that the text cursor jumps to the end.

This problem occurs only when typing or pasting Farsi and Arabic. What do you think is the problem? can you solve it?

Only when he wants to choose two or three numbers from among the numbers and change them. By writing the first number, it jumps to the end, and then the second digit, which should have been written next to the first digit in the same place he had chosen, goes to the end, and this messes up everything. If you test, you will see that there is no such problem with English.

Un DOMException: Failed to load because no supported source was found. Failed to load resource: the server responded with a status of 404 (Not Found)

  1. we have contained 6 songitems in songlist container that allready contained is in container class
  2. i want to access all song item by using js code but i can’t do this.

best of ncps-No copy pest sound

let me love you
05:30


i am not faceing any errors of block of this code
but my medea source is not accessing by js
if anybody have an about solution plese help

let songindex=0; 
let AudioElement=new Audio("music/01 - Jab Se Mera Dil - Amavas.mp3");
let masterPlay=document.getElementById("masterplay");
let myprogressBar=document.getElementById("myprogressBar");
let Gif=document.getElementById("Gif");
let songitems=Array.from(document.getElementsByClassName('songitems'));
let songs=[
        {songName:"1.jab se mera dil", filepath:"music/01 - Jab Se Mera Dil - Amavas.mp3", coverpath:"image/cover0.jpg"},
        {songName:"2.soch na sake", filepath:"music/01 - Soch Na Sake(wapking.fm).mp3", coverpath:"image/covr1.jpg"},
        {songName:"3.dhadak", filepath:"music/01 Dhadak - Title Song.mp3", coverpath:"image/cover3.jpg"},
        {songName:"4.Dil m.Chahe", filepath:"music/01 Dil mera chahe.mp3", coverpath:"image/cover4.jpg"},
        {songName:"5.ek mulakat", filepath:"music/01 EK Mulaqat - Sonali Cable (PagalWorld.com) 320Kbps.mp3", coverpath:"image/cover5.jpg"},
        {songName:"6.sanso ko", filepath:"music/02- Saanson Ko.mp3", coverpath:"image/cover6.jpg"},
]
songitems.forEach(function (element, i) {
        //console.log(element,i);
        element.getElementsByTagName('img')[0].src= songs[i].coverpath;
        element.getElementsByClassName('songName')[0].innerText = songs[i].songName;
})
//handel play//pouse play
masterPlay.addEventListener('click',()=>{
        if(AudioElement.paused || AudioElement.currentTime<=0){
                AudioElement.play();
                masterPlay.classList.remove('fa-circle-play');
                masterPlay.classList.add('fa-circle-pause');
                Gif.style.opacity=1;
        }
         else{
                AudioElement.pause();
                masterPlay.classList.remove('fa-circle-pause');
                masterPlay.classList.add('fa-circle-play');
                Gif.style.opacity=0;

        }
Array.from(document.getElementsByClassName("songItemPlay")).forEach((element)=>{
        element.addEventListener('click',(e)=>{
               // console.log(e.target);
                makeAllplay();
                index=parseInt(e.target.id);//---e.target.id
                e.target.classList.remove('fa-circle-play');
                e.target.classList.add('fa-circle-pause');
                AudioElement.src=`music/${index+1}.mp3`; //here is access medea by using of event.targrt.id
                AudioElement.currentTime=0;
                AudioElement.play();
                masterPlay.classList.remove('fa-circle-play');
                masterPlay.classList.add('fa-circle-pause');
        });
})

Is there a way to pass attributes to Vue JS computed getter/setter?

I am trying to use computed property to bind my input fields with the Vuex Store.
So I have Data Streams and each of them have specific input fields, they aren’t fixed but managed from the admin section of the application, and I have to provide to the users functionality that user will select specific data stream and then inputs will be shown as received from the API.

I have tried to achieve that but here is my blocker. Computed properties (getters) cannot receive attributes so I cannot tell the vuex getter which data to return.

Please find bellow the code I have used, Is there some other way to achieve the same functionality?

Vue JS Component – Input fields

<v-text-field
    :key="input_index"
    v-model="data_stream_inputs[ds_index][input_index]"
    :label="input.name"
    :placeholder="input.placeholder"
></v-text-field>

Computed properties (not working properly)

computed: {
    data_stream_inputs: {
        get() {
            return this.$store.getters['ActivateAudienceStore/getDataStreamInputByIndex'],
        set(value) {
            this.$store.commit('ActivateAudienceStore/SET_DATASTREAM_INPUT_BY_INDEX', value)
        }
    }
}

Getter

export const getDataStreamInputByIndex = (state) => (payload) => {
    return state.data_delivery.datastreams[payload.data_stream].inputs[payload.index]
}

nestjs: for each module, inject a different provider into a controller without providers interfering

I have the following nestjs classes and modules. Each module uses the same controller, but a different provider is injected into the controller for each module. I may not be using the nestjs’ dependency injection framework properly, but what happens is that the last injected service (ServiceC) appears in each of the modules. Is there a way to stop this interference from happening? I’ve tried injecting using useFactory but to no avail. I would like each module to inject a unique service that extends MyAbstractService as described below.

    export class MyController {
      constructor(
        @Inject("COMMON_SERVICE") private readonly commonService: MyAbstractService,
      ) {
      commonService.doSomething();
      }
    }
    @Injectable()
    export class ServiceA extends MyAbstractService {
      public doSomething(){
      }
    }

    @Injectable()
    export class ServiceB extends MyAbstractService {
      public doSomething(){
      }
    }

    @Injectable()
    export class ServiceC extends MyAbstractService {
      public doSomething(){
      }
    }
    @Module({
      controllers: [MyController],
      providers: [
        {
          provide: "COMMON_SERVICE",
          useClass: ServiceA,
        },
    ]})
    export class ModuleA

    @Module({
      controllers: [MyController],
      providers: [
        {
          provide: "COMMON_SERVICE"
          useClass: ServiceB,
        },]
    })
    export class ModuleB

    @Module({
      controllers: [MyController],
      providers: [
        ...commonProviders,
        {
          provide: "COMMON_SERVICE"
          useClass: ServiceC,
        },]
    })
    export class ModuleC

And finally a main module

@Module({
  imports: [
    ModuleA,
    ModuleB,
    ModuleC
  ],
  controllers: [],
  providers: [],
})
export class MainModule {}
function main(){
  const app = await NestFactory.create(MainModule);
}

Context not working in React.js when the page is refreshed

This is an e-commerce website.

<Route path='products/:productId' element={<Product />} />

Here I am using react dynamic route for showing product’s details when clicked on a product.

I have a ShopContext.jsx file which gets all the products from the server and provides to the other components when needed. Here is the part of that code in my ShopContext.jsx file:

const [all_product, setAll_Product] = useState([]);
    useEffect(() => {
        fetch(`${process.env.REACT_APP_SERVER_API}/allproducts`)
        .then((res) => res.json())
        .then((data) => setAll_Product(data));
....
}, []) 

This one below is my main product page:

const Product = () => {

     const {all_product} = useContext(ShopContext);

    const {productId} = useParams();

    const product = all_product.find((e)=> e.id === Number(productId))

  return (
    <div>
        <ProductDisplay product = {product}/>
        <DescriptionBox/>
        <RelatedItems/>
    </div>
  )
}

export default Product;

It passes the ‘product’ to the product display component and the product display component renders that .
but when i refresh the page the ‘product’ param becomes undefined. it says, “product is undefined”. why? and how to solve this?

Edit: Here is the full shop context file:

mport React, { createContext, useEffect, useState } from "react";


export const ShopContext = createContext(null);

const getDefaultCart = ()=>{
    let cart = {};
    for(let i = 0; i < 300 + 1; i++) {
        cart[i] = 0;
    }
    return cart;
}

const ShopContextProvider = (props) => {
    const [all_product, setAll_Product] = useState([]);

    const [cartItems, setCartItems] = useState(getDefaultCart());

    useEffect(() => {
        fetch(`${process.env.REACT_APP_SERVER_API}/allproducts`)
        .then((res) => res.json())
        .then((data) => setAll_Product(data));

        console.log("context  "+all_product);

        if(localStorage.getItem('auth-token')) {
            fetch(`${process.env.REACT_APP_SERVER_API}/getcart`, {
                method: 'POST',
                headers: {
                    Accept: 'application/form-data',
                    'auth-token': `${localStorage.getItem('auth-token')}`,
                    'content-type': 'application/json'
                },
                body: ""
            })
            .then((res) => res.json())
            .then((data) => setCartItems(data));
        }
    }, []) 

    const addToCart = (itemId) => {
        setCartItems((previous) => ({...previous,[itemId]:previous[itemId] + 1}));
        if(localStorage.getItem('auth-token')) {
            fetch(`${process.env.REACT_APP_SERVER_API}/addtocart`, {
                method: "POST",
                headers: {
                    Accept: "application/form-data",
                    'auth-token':  `${localStorage.getItem('auth-token')}`,
                    'content-type': "application/json",
                },
                body: JSON.stringify({"itemId" : itemId})
            })
            .then((res) => res.json())
            .then((data) => console.log(data));
        }
    }

    const removeFromCart = (itemId) => {
        setCartItems((previous) => ({...previous,[itemId]:previous[itemId] - 1}));
        if(localStorage.getItem('auth-token')) {
            fetch(`${process.env.REACT_APP_SERVER_API}/removefromcart`, {
                method: "POST",
                headers: {
                    Accept: "application/form-data",
                    'auth-token':  `${localStorage.getItem('auth-token')}`,
                    'content-type': "application/json",
                },
                body: JSON.stringify({"itemId" : itemId})
            })
            .then((res) => res.json())
            .then((data) => console.log(data));
        }
    }

    const deleteFromCart = (itemId) => {
        setCartItems((previous) => ({...previous,[itemId]:0}));
        if(localStorage.getItem('auth-token')) {
            fetch(`${process.env.REACT_APP_SERVER_API}/deletefromcart`, {
                method: "POST",
                headers: {
                    Accept: "application/form-data",
                    'auth-token':  `${localStorage.getItem('auth-token')}`,
                    'content-type': "application/json",
                },
                body: JSON.stringify({"itemId" : itemId})
            })
            .then((res) => res.json())
            .then((data) => console.log(data));
        }
    }

    const getTotalCartAmount = () => {
        let totalAmount = 0;
        for(const item in cartItems) {
            if(cartItems[item] > 0) {
                let itemInfo = all_product.find((product) => product.id === Number(item));
                totalAmount += itemInfo.new_price * cartItems[item];
            }
        }
        return totalAmount;
    }

    const getTotalCartItems = () => {
        let totalItems = 0;
        for(const item in cartItems) {
            if(cartItems[item] > 0) {
                totalItems += cartItems[item];
            }
        }
        return totalItems;
    }
    
    const contextValue = {all_product, cartItems, addToCart, removeFromCart, deleteFromCart, getTotalCartAmount, getTotalCartItems};
    return (
        <ShopContext.Provider value = {contextValue}>
            {props.children}
        </ShopContext.Provider>
    )
}

export default ShopContextProvider;

Javascript adding to an array

I have an object like this, that contains a lot more data than what is present but this is just a small sample.

I am iterating through the object and checking if EmployeeLocations = object. If it does, I would like to add that to a new array along with the nested value. For example, “EmployeeLocationA : FL HQ” would be added to the array, “EmployeeLocationB” : “New York”, “DoorsA” : 345, would be added and so forth.

This array will be joined with the values of the original array and returned.

{
  "Building": 4,
  "Doors":{
   "a": 345,
   "b": 87,
   "c": 98
  }
  "EmployeeId": 565,
  "EmployeeLocation": {
    "a": "FL HQ",
    "b": "New York",
    "c": "Chicago"
  },

I am able to iterate and get the following information, but I am unable to add it to the array. What I am trying to get back is an array that looks like this:

 "Building": 4, "DoorsA": 345, "DoorB": 87, "DoorsC": 98, "EmployeeId": 565, "EmployeeLocationA": "FL HQ", "EmployeeLocationB": "New York", "EmployeeLocationC": "Chicago" ,
  Object.keys(Details).forEach((key, value) => {
    if(typeof( Details[key]) === 'object' ){
      const objPositions = Details[key]; // holds inner values
      console.log("objposition " + objPositions[key] + allDetails[key])
      console.log("---->" + key + "X " + objPositions.x);
      console.log("---->" + key + "Y " + objPositions.y);
      console.log("---->" + key + "Z " + objPositions.z);
      let xKey = key + "X"
      arr.push(key + "X" , objPositions.x)
     // arr.push(xKey.toString() : objPositions.x.toString())

I am really new at javascript and am having big trouble with it. Can someone shed a little light? Thanks