Axios doesn’t post data to mongodb

I’m building an E-Commerce site using ReactJs and MongoDB, and now i’m building a success.jsx page (a page that show up right after a sucessfull pay with Stripe).

Upon loading this page, it should create the order (you can call it a facture) that the client made and post it to database (MongoDB).

my backend is tested and worked just fine, i can post cart data into my MongoDB.

My problem is that my request to post a new order (axios) doesn’t work, even thought the token is new generated with duration 90 days.

console.dev shows this only error after adding catch (err) in cart.jsx page:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘data’)

How to fix it?

Success.jsx code:

import { useEffect, useState } from "react";
import { useLocation } from "react-router";
import { userRequest } from "../requestMethods";

const Success = () => {
  const location = useLocation();
  const data = location.state.stripeData;
  const cart = location.state.cart;
  const [orderId, setOrderId] = useState(null);

  useEffect(() => {
    const createOrder = async () => {
      try {
        const res = await userRequest.post("orders/add", {
          products: cart.products.map((item) => ({
            productId: item._id,
            quantity: item._quantity,
          })),
          amount: cart.total,
          address: data.billing_details.address,
        });
        setOrderId(res.data._id);
      } catch (err) {
          console.log(err.response.data);
      }
    };
    data && createOrder();
  }, [cart, data]);
  return (
    //...
  )
export default Success;

RequestMethods.js code:

import axios from "axios";

const BASE_URL = 'http://localhost:5000/api/';
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpKNpc...";

export const publicRequest = axios.create({
    baseURL: BASE_URL,
});

export const userRequest = axios.create({
    baseURL: BASE_URL,
    header: { token: `Bearer ${TOKEN}` }
});

Backend:

Order.js code:

const router = require("express").Router();
const Order = require("../models/Order");
const { verifyToken, verifyTokenAndAuthorization, verifyTokenAndAdmin } = require("./verifyToken")

//ADD Order
router.post("/add", verifyToken, async (req, res) => {
    const newOrder = new Order(req.body)
    try {
        const addedOrder = await newOrder.save();
        res.status(200).json(addedOrder);
    } catch (err) {
        res.status(500).json(err);
    }
});
module.exports = router;

index.js code:

//...
app.use("/api/orders", orderRoute);
//...

I have a problem with the component loading after making a search using query parameters

In my application, I have a form that is supposed to search for the workout components that I have displayed based on two fields: category and difficulty. When I search, I can see that the URL changes properly, but the cards are not filtered at all. They disappear.
Below I have the code for the component where the search is made:

import React, {useState, useEffect} from 'react'
import {Container,  Grow, Grid, Paper, AppBar,TextField,Button, TextareaAutosize} from '@material-ui/core';
import {useDispatch} from 'react-redux';
import {getWorkouts, getWorkoutsBySearch} from '../../actions/workouts';
import {useNavigate, useLocation, Navigate} from 'react-router-dom';
import ChipInput from 'material-ui-chip-input'

import Workouts from "../Workouts/Workouts";
import Pagination from '../Pagination';
import Form from "../Form/Form";
import useStyles from './styles';

function useQuery(){
    return new URLSearchParams(useLocation().search);
}


function Home() {
    const [currentId, setCurrentId]=useState(null);
    const classes=useStyles();
    const dispatch=useDispatch();
    const query=useQuery();
    const history=useNavigate();
    const page=query.get('page') || 1;
    const searchQuery=query.get('searchQuery');
    const [search, setSearch] = useState('');
    const [category, setCategory] = useState([]);

    const searchWorkout=()=>{
        if(search.trim() || category){
            dispatch(getWorkoutsBySearch({search, category:category.join(',')}));
            history(`/workouts/search?searchQuery=${search || 'none'} & category=${category.join(',')}`)
        }else{
            history(`/workouts`);
        }
    }

    useEffect(()=>{
        dispatch(getWorkouts());
    },[currentId, dispatch]);

    const handleKeyPress=(e)=>{
        if(e.keyCode===13){
            searchWorkout();
        }
    }

    const handleAdd=(categ)=>setCategory([...category,categ]);

    const handleDelete=(categoryToDelete)=>setCategory(category.filter((categ)=>categ!==categoryToDelete));
    
    const user = JSON.parse(localStorage.getItem("profile"));
  return (
    <Grow in>
                <Container maxWidth="xl">
                    <Grid className={classes.gridContainer} container justifyContent="space-between" alignItems='stretch' spacing={3}>
                        <Grid item xs={12} sm={6} md={9}>
                            <Workouts  setCurrentId={setCurrentId}/>
                        </Grid>
                        <Grid item xs={12} sm={6} md={3}>
                        <AppBar className={classes.appBarSearch} position="static" color="inherit">
                            <TextField
                                name="search"
                                variant="outlined"
                                label="Search workouts"
                                onKeyPress={handleKeyPress}
                                fullWidth
                                value={search}
                                onChange={(e)=>setSearch(e.target.value)}
                            />
                            <ChipInput
                                style={{margin:'10px 0'}}
                                value={category}
                                onAdd={handleAdd}
                                onDelete={handleDelete}
                                label="Search Category"
                                variant="outlined"
                            />
                            <Button onClick={searchWorkout} className={classes.searchButton} variant="contained" color="primary">Search</Button>
                        </AppBar>
                        {
                                user?.result?.email.endsWith('admin.com')?
                                <>
                                <Form currentId={currentId} setCurrentId={setCurrentId}/>
                                <Paper className={classes.pagination} levation={6}>
                                    <Pagination/>
                                </Paper>
                                </>
                                :<></>
                        }
 
                        </Grid>
                    </Grid>
                </Container>
            </Grow>
  )
}

export default Home

Here I have the actions code that is supposed to handle the workouts loading on the page.

import { FETCH_ALL, FETCH_BY_SEARCH, CREATE, UPDATE, DELETE, LIKE, COMMENT_WORKOUT, COMMENT_MEAL, MARK_WORKOUT_AS_COMPLETE, GET_USER_DATA } from '../constants/actionTypes';

import * as api from '../api';

export const getWorkouts=()=> async (dispatch)=>{
    try{
        const data=await api.fetchWorkouts();

        dispatch({type:FETCH_ALL,payload:data});
    }catch(error){
        console.log(error);
    }

}

export const getWorkoutsBySearch=(searchQuery)=>async(dispatch)=>{
    try{
        const {data: {data}}=await api.fetchWorkoutsBySearch(searchQuery);

        dispatch({type:FETCH_BY_SEARCH,payload:data});
    }catch(error){
        console.log(error);
    }
}

export const createWorkout=(workout)=>async(dispatch)=>{
    try{
            const data=await api.createWorkout(workout);

            dispatch({type:CREATE,payload:data});
    }catch(error){
            console.log(error.message);
    }
}

export const updateWorkout=(id,workout)=>async(dispatch)=>{
    try{
        const data=await api.updateWorkout(id,workout);

        dispatch({type:UPDATE,payload:data})
        
    }catch(error){
        console.log(error);
    }
}

export const deleteWorkout = (id) => async (dispatch) => {
    try {
      await api.deleteWorkout(id);
  
      dispatch({ type: DELETE, payload: id });
    
    } catch (error) {
      console.log(error);
    }
  };

export const likeWorkout=(id)=>async(dispatch)=>{
    try{
        const data=await api.likeWorkout(id);
        dispatch({type:LIKE,payload:data})
    }catch(error){
        console.log(error);
    }
}

export const postCommentOnWorkout=(data)=>async(dispatch)=>{
    try{
        const res=await api.postCommentOnWorkout(data);
        dispatch({type:COMMENT_WORKOUT,payload:res})
    }catch(error){
        console.log(error);
    }
}

export const markWorkoutAsComplete=(data)=>async(dispatch)=>{
    try{
        
        const res=await api.markWorkoutAsComplete(data);
        dispatch({type:MARK_WORKOUT_AS_COMPLETE,payload:res})
    }catch(error){
        console.log(error);
    }
}

export const postCommentOnMeal=(data)=>async(dispatch)=>{
    try{
        const res=await api.postCommentOnMeal(data);
        dispatch({type:COMMENT_MEAL,payload:res})
    }catch(error){
        console.log(error);
    }
}


export const getUserDetails=()=>async(dispatch)=>{
    try{
        dispatch({type:GET_USER_DATA})
    }catch(error){
        console.log(error);
    }
}

The reducer for this action is this one:

case FETCH_BY_SEARCH:
    return action. payload;

The back-end code with the requests from the backend is this one:

import express from "express";
import mongoose from "mongoose";
import WorkoutMessage from "../models/workoutMessage.js";
import User from "../models/user.js";

const router = express.Router();

export const getWorkouts = async (req, res) => {
  try {
    const workoutMessages = await WorkoutMessage.find();

    res.status(200).json(workoutMessages);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
};

export const getWorkoutsBySearch = async (req, res) => {
  const { searchQuery, category } = req.query;

  try {
      const difficulty = new RegExp(searchQuery, "i");

      const workouts = await WorkoutMessage.find({ $or: [ { category }, { difficulty } ]});

      res.json({ data: workouts });
  } catch (error) {    
      res.status(404).json({ message: error.message });
  }
}

export const createWorkout = async (req, res) => {
  const workout = req.body;

  const newWorkoutMessage = new WorkoutMessage({
    ...workout,
    creator: req.userId,
    createdAt: new Date().toISOString(),
  });
  try {
    await newWorkoutMessage.save();

    res.status(201).json(newWorkoutMessage);
  } catch (error) {
    res.status(409).json({ message: error.message });
  }
};

export const updateWorkout = async (req, res) => {
  const { id: _id } = req.params;
  const workout = req.body;

  if (!mongoose.Types.ObjectId.isValid(_id))
    return res.status(404).send(`No workout with that ${_id}`);

  const updatedWorkout = await WorkoutMessage.findByIdAndUpdate(
    _id,
    { ...workout, _id },
    { new: true }
  );

  res.json(updateWorkout);
};

export const deleteWorkout = async (req, res) => {
  const { id } = req.params;

  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send("No workout with that id");

  await WorkoutMessage.findByIdAndRemove(id);

  res.json({ message: "Workout deleted successfully" });
};

export const likeWorkout = async (req, res) => {
  const { id } = req.params;

  if (!req.userId) return res.json({ message: "Unauthenticated" });

  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send("No workout with that id");

  const workout = await WorkoutMessage.findById(id);

  const index = workout.likes.findIndex((id) => id === String(req.userId));

  if (index === -1) {
    workout.likes.push(req.userId);
  } else {
    workout.likes = workout.likes.filter((id) => id != String(req.userId));
  }

  const updatedWorkout = await WorkoutMessage.findByIdAndUpdate(id, workout, {
    new: true,
  });

  res.json(updatedWorkout);
};

export const commentOnWorkout = async (req, res) => {
  const { userId, workoutId, userName, comment } = req.body;
  const workout = await WorkoutMessage.findById(workoutId);

  if (workout) {
    User.findOne({ _id: userId }).then(async (user) => {
      if (user) {
        const commentObject = {
          commentedBy: userId,
          commentor: userName,
          comment: comment,
        };
        const updatedWorkout = await WorkoutMessage.updateOne(
          { _id: workoutId },
          {
            $push: {
              comments: commentObject,
            },
          }
        );

        const workouts = await WorkoutMessage.findById(workoutId);
        res.send({ data: workouts });
      }
    });
  }
};

export const markWorkoutAsComplete = async (req, res) => {
  const { userId, workoutId, status } = req.body;
  console.log("MARK AS complete API hit", status);

    await User.findOneAndUpdate({ _id:userId},
        {
          $set: {
            completedWorkouts: {
              status: status,
              workoutId:workoutId
            },
          },
        },
        { upsert: true }
      );

        const user2 = await User.findById(userId);
        console.log(user2)
        res.send({ data: user2 });
};
export default router;

I cannot see where the problem is coming from. Could you help me solve this?

Please How do I use JavaScript to open and hide a div when I click on a button below it [duplicate]

I have a div of id=”hiddenVideos” containing videos, and a button of show more at the bottom of the div. But I want a situation that when I click on the show more button it will show the contents inside the #hiddenVideos div tag and the content of the button will change to “show less” so that when I click on it again the #hiddenVideos div tag will be hidden again.

Update object inside an array in useState React

I have an object in useState that has an array inside called detail. This array contains objects that I need to update for example to change quantities or purchase prices.

createdAt: "2022/07/15"
detail: Array(2)
0:
name: "LINK AZUL"
provider: {uid: '6271a32082193f4b88e292f0', name: 'Genérico'}
purchasePrice: 195
quantity: 3
subtotal: 585
total: 0
_id: "62ab8f3cd0519268de938c8f"
[[Prototype]]: Object
1: {provider: {…}, _id: '62ab8ed6d0519268de938bc9', name: 'LINK ROJO', quantity: 3, purchasePrice: 186, …}
length: 2
[[Prototype]]: Array(0)
disabledBy: []
discount: 10
idProvider: {_id: '6271a32082193f4b88e292f0', name: 'Genérico'}

How can I access the _id of the object inside the detail array to be able to modify it and set it in useState?

I have tried with this code where I search for _id but then I don’t know how to set it in the array of objects called detail so that only that object is modified without altering the rest
Besides that I think it will not work properly.

const onChangePriceHandler = (id, e) => {
        let newPrice = Number(e.target.value)
       
        const updatePrice = products.detail?.map(data => {
          if (data.id === id) {
            return {
              ...data, purchasePrice: newPrice, subtotal: newPrice * data.quantity
            }
        } 
            return data
        })
        setProducts( /* ?? */)
      }

My env variable works on localhost but is undefined when deployed on Netlify

Having trouble getting an axios GET request to work on Netlify because the env variable that defines my api key comes up as undefined on Netlify. I have already set the env variable with ‘Site settings > Build & deploy > Environment > Environment variables’. But when I try it on Netlify I get:

GET https://api.openweathermap.org/data/2.5/forecast?q=London&appid=undefined&units=imperial
error forecast: AxiosError: Request failed with status code 401

Here is my code that makes the GET request:

import { Forecast } from './forecast';
import axios from 'axios';

export class DOM {
    static displayFiveDayForecast = (city) => {
        const BASE_URL_FIVE_DAY_FORECAST = 'https://api.openweathermap.org/data/2.5/forecast';

        axios.get(`${BASE_URL_FIVE_DAY_FORECAST}?q=${city}&appid=${process.env.API_KEY}&units=imperial`)
        .then(res => {
            const weatherObj = Forecast.createForecasts(res.data);
            const content = document.getElementById('content');

            const forecastDiv = document.createElement('div');
            forecastDiv.id = 'forecast';
            content.appendChild(forecastDiv);

            for(let value in weatherObj.forecasts) {
                const forecastBox = document.createElement('div');
                forecastBox.className = 'forecast-item';
                forecastDiv.appendChild(forecastBox);

                const date = document.createElement('div');
                date.textContent = weatherObj.forecasts[value][0];
                forecastBox.appendChild(date);

                const icon = document.createElement('img');
                icon.src = weatherObj.forecasts[value][3];
                icon.alt = 'forecast icon';
                forecastBox.appendChild(icon);

                const main = document.createElement('div');
                main.textContent = `${weatherObj.forecasts[value][1]} Fu00B0`;
                forecastBox.appendChild(main);

                const feelsLike = document.createElement('div');
                feelsLike.textContent = `Feels like ${weatherObj.forecasts[value][2]} Fu00B0`;
                forecastBox.appendChild(feelsLike);
            }
        })
        .catch(err => {console.log(`error forecast: ${err}`)})
    }
}

This GET request works fine on localhost and the api key is defined there. I’m using webpack if that information helps.

Should I use a CMS just to implement a basic feature to a dynamic website?

I am here today to ask a question about a potential client I could have lined up. The website is pretty simple in itself, informational.

The client has requested that they are able to add and remove products from a page, but they aren’t really products. They are just a showcase, kind of like a portfolio of what products they sell. The don’t want a purchase option, as it’s only a small business.

  • I have a good knowledge of Javascript and MySQL
  • I have never really touched a CMS (was going for WordPress)
  • This task seems like something that can be implemented with a little amount of code

Would It really be with the hassle of me learning WordPress and CMS in general just to produce a portfolio type of page?

Ok let’s narrow this down.

I have experience in the following fields:

  • HTML, CSS, Javascript, MySQL
  • React JS

The questions:

  • Is it worth my time learning a CMS just to implement a basic input system for a portfolio?

  • Is it possible in Javascript, or am I going to have to create some sort of micro-CMS program for the client to create new products?

  • If anyone can answer, really, what’s the best way of approaching this?

I appreciate any answers I get, I am sorry I ramble on a little bit but I really can’t get my head around how to do this.

Many Thanks!

Changing div z-index when dropdown is opened

I’m developing a laravel project and I got stuck somewhere. I wanted to ask you people who know.

When I open a dropdown menu, I want to change the z-index parameter of another div class. I want the z-index to be restored when dropdown is closed.

nav dropdown

<div class="nav-item dropdown">
                <a href="#" class="nav-link d-flex lh-1 text-reset p-0" data-bs-toggle="dropdown" aria-label="Open user menu" aria-expanded="false">
                                        <span class="avatar avatar-sm" style="background-image: url(http://localhost/storage/avatar/1654729156.png)"></span>
                                        <div class="d-none d-xl-block ps-2">
                        <div>x</div>
                        <div class="mt-1 small text-muted">xxx@g...</div>
                    </div>
                </a>
              
                <div class="dropdown-menu dropdown-menu-end dropdown-menu-arrow">
                    <a href="http://localhost/profile/x" class="dropdown-item">Profil</a>
                    <a href="http://localhost/kaydedilenler" class="dropdown-item">Kaydedilenler</a>
                    <div class="dropdown-divider"></div>
                    <a href="http://localhost/hesap/düzenle" class="dropdown-item">Hesap</a>
                                                            <a href="http://localhost/logout" class="dropdown-item" onclick="event.preventDefault();
                                document.getElementById('logout-form').submit();">Çıkış Yap</a>
                    <form id="logout-form" action="http://localhost/logout" method="POST">
                        <input type="hidden" name="_token" value="kBUQFXTwUu3m13f">                    </form>
                </div>
            </div>

The navbar with the z-index I want to change

<div class="navbar-expand-md sticky-top shadow">
    <div class="collapse navbar-collapse" id="navbar-menu">
        <div class="navbar navbar-dark">
            <div class="container-xl">
                <ul class="navbar-nav">
                    <li class="nav-item active">
                        <a class="nav-link strong" href="http://localhost">
                            <span class="nav-link-icon d-lg-inline-block">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><line x1="4" y1="6" x2="13" y2="6"></line><line x1="4" y1="12" x2="11" y2="12"></line><line x1="4" y1="18" x2="11" y2="18"></line><polyline points="15 15 18 18 21 15"></polyline><line x1="18" y1="6" x2="18" y2="18"></line></svg>
                            </span>
                            <span class="nav-link-title">
                                En Son
                            </span>
                        </a>
                    </li>
                    
                    <li class="nav-item ">
                        <a class="nav-link strong" href="http://localhost/viral">
                            <span class="nav-link-icon d-lg-inline-block">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><line x1="3" y1="12" x2="6" y2="12"></line><line x1="12" y1="3" x2="12" y2="6"></line><line x1="7.8" y1="7.8" x2="5.6" y2="5.6"></line><line x1="16.2" y1="7.8" x2="18.4" y2="5.6"></line><line x1="7.8" y1="16.2" x2="5.6" y2="18.4"></line><path d="M12 12l9 3l-4 2l-2 4l-3 -9"></path></svg>
                            </span>
                            <span class="nav-link-title">
                                Viral
                            </span>
                        </a>
                    </li>
                    
                    <li class="nav-item ">
                        <a class="nav-link strong" href="http://localhost/random">
                            <span class="nav-link-icon d-lg-inline-block">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" style="" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M3 17h5l1.67 -2.386m3.66 -5.227l1.67 -2.387h6"></path><path d="M18 4l3 3l-3 3"></path><path d="M3 7h5l7 10h6"></path><path d="M18 20l3 -3l-3 -3"></path></svg>
                            </span>
                            <span class="nav-link-title">
                                Rastgele
                            </span>
                        </a>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#sidebar-authentication" data-bs-toggle="dropdown" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-lg-inline-block">
                            <i class="fa-solid fa-hands-bound" style=""></i>
                            </span>
                            <span class="nav-link-title">
                            Kategoriler
                            </span>
                            
                        </a>
                        <div class="dropdown-menu">
                                                                                        <a class="dropdown-item" href="http://localhost/category/genel">
                                                Genel
                                            </a>
                                                                                    </div>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#navbar-extra" data-bs-toggle="dropdown" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-lg-inline-block">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><circle cx="9" cy="7" r="4"></circle><path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path><path d="M21 21v-2a4 4 0 0 0 -3 -3.85"></path></svg>
                            </span>
                            <span class="nav-link-title">
                                Cinsiyet
                            </span>
                        </a>
                        <div class="dropdown-menu">
                                                        <a class="dropdown-item" href="http://localhost/gender/1/erkek">
                                Erkek
                            </a>
                                                    </div>
                    </li>
                    
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#sidebar-authentication" data-bs-toggle="dropdown" role="button" aria-expanded="false">
                            <span class="nav-link-icon d-lg-inline-block">
                            <i class="fa-solid fa-file-lines" style=""></i>
                            </span>
                            <span class="nav-link-title">
                            Sayfalar
                            </span>
                            
                        </a>
                        <div class="dropdown-menu">
                                                                                        <a href="http://localhost/page/sartlar-ve-politikalar" class="dropdown-item text-truncate">
                                                sartlar ve Politikalar
                                            </a>
                                                                                        <a href="http://localhost/page/iletisim" class="dropdown-item text-truncate">
                                                iletisim
                                            </a>
                                                                                        <a href="http://localhost/page/hos-geldiniz" class="dropdown-item text-truncate">
                                                hoş geldiniz
                                            </a>
                                                                                    </div>
                    </li>
                </ul>
                <div class="my-2 my-md-0 flex-grow-1 flex-md-grow-0 order-first order-md-last">
                    <a href="#" class="btn btn-white btn-pill strong" data-bs-toggle="modal" data-bs-target="#modal--write--story">
                        <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><circle cx="12" cy="12" r="9"></circle><line x1="9" y1="12" x2="15" y2="12"></line><line x1="12" y1="9" x2="12" y2="15"></line></svg> Bir şeyler yaz
                    </a>
                </div>
            </div>
            
        </div>
        
    </div>

    
</div>

summarize a function that selects multiple elements

I made a function that changed the colors of my site when I clicked (a light-mode-theme), and with that, I had to select the elements that would have their colors changed, one by one, which left the code huge. how could i summarize this selection?

    let h = document.querySelector('header');
    h.classList.toggle('bright-mode');
    let b = document.querySelector('body');
    b.classList.toggle('bright-mode');
    let h1 = document.querySelector('h1');
    h1.classList.toggle('bright-mode');
    let h2 = document.querySelector('h2');
    h2.classList.toggle('bright-mode');
    let h3 = document.querySelector('h3');
    h3.classList.toggle('bright-mode');
    let h4 = document.querySelector('h4');
    h4.classList.toggle('bright-mode');
    let si = document.querySelector('.section-inicio');
    si.classList.toggle('bright-mode');
    let ss = document.querySelector('.section-sobre');
    ss.classList.toggle('bright-mode');
    let sl = document.querySelector('.section-linguagens');
    sl.classList.toggle('bright-mode');
}

change color of many squares seperatly to different colors by clicking with JavaScript

I’m new to JavaScript and I’m trying to change the colour of a square by clicking on it, first to yellow, then orange, then green and back to white. So far I managed to do that for one row, but if I want to add a 2nd row, a 3rd, a 4th, till atleast a 100th, it says I can’t use the same Id-tag. So what other options do I have?

I tried to work with document.getElementsByTagName (“container”); and document.getElementsByClassName(“container”); but for some reason the colour doesn’t change anymore after that.

I hope someone can help me. Thanks in advance!

let x = document.getElementById("container");
let y = x.children;
let click = 0;

function myFunction() {
  for (let i = 0; i < y.length; i++) {
    y[i].onclick = function() {
      if (click == 0) {
        y[i].style.backgroundColor = "yellow";
        click = 1;
      } else if (click == 1) {
        y[i].style.backgroundColor = "orange";
        click = 2;
      } else if (click == 2) {
        y[i].style.backgroundColor = "green";
        click = 3;
      } else {
        y[i].style.backgroundColor = "white";
        click = 0;
      }
    }
  }
}
myFunction();
div {
  background-color: white;
  text-align: center;
  float: left;
}

* {
  box-sizing: border-box;
}

.header {
  border: 1px solid gray;
  padding: 15px;
  width: 100%;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

[class*="col-"] {
  float: left;
  padding: 20px;
  height: 15px;
  border: 1px solid grey;
}

.col-1 {
  min-width: 20%;
}

.col-2 {
  min-width: 4%;
}

.col-3 {
  min-width: 4%;
}

.col-4 {
  width: 4%;
}

.col-5 {
  width: 4%;
}

.col-6 {
  width: 4%;
}

.col-7 {
  width: 4%;
}

.col-8 {
  width: 4%;
}

.col-9 {
  width: 4%;
}

.col-10 {
  width: 4%;
}

.col-11 {
  width: 4%;
}

.col-12 {
  width: 4%;
}

.col-13 {
  width: 4%;
}

.col-14 {
  width: 4%;
}

.col-15 {
  width: 4%;
}

.col-16 {
  width: 4%;
}

.col-17 {
  width: 4%;
}

.col-18 {
  width: 4%;
}

.col-19 {
  width: 4%;
}

.col-20 {
  width: 4%;
}

.col-21 {
  width: 4%;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>test</title>
</head>

<body>
  <div class="header">Goals</div>
  <div class="row">
    <div class="col-1">Names:</div>
    <div class="col-2">AA</div>
    <div class="col-3">AA</div>
    <div class="col-4">FA</div>
    <div class="col-5">AA</div>
    <div class="col-6">OB</div>
    <div class="col-7">DB</div>
    <div class="col-8">DG</div>
    <div class="col-9">MK</div>
    <div class="col-10">GM</div>
    <div class="col-11">BM</div>
    <div class="col-12">SM</div>
    <div class="col-13">LN</div>
    <div class="col-14">ER</div>
    <div class="col-15">SR</div>
    <div class="col-16">YS</div>
    <div class="col-17">MT</div>
    <div class="col-18">ST</div>
    <div class="col-19">ST</div>
    <div class="col-20">JV</div>
    <div class="col-21">EZ</div>
  </div>

  <div class="row">
    <div class="col-1">Ik learn how to count till 10.</div>
    <div id="container">
      <div class="col-2"> </div>
      <div class="col-3"> </div>
      <div class="col-4"> </div>
      <div class="col-5"> </div>
      <div class="col-6"> </div>
      <div class="col-7"> </div>
      <div class="col-8"> </div>
      <div class="col-9"> </div>
      <div class="col-10"> </div>
      <div class="col-11"> </div>
      <div class="col-12"> </div>
      <div class="col-13"> </div>
      <div class="col-14"> </div>
      <div class="col-15"> </div>
      <div class="col-16"> </div>
      <div class="col-17"> </div>
      <div class="col-18"> </div>
      <div class="col-19"> </div>
      <div class="col-20"> </div>
    </div>
  </div>

When running getting: TypeError: Cannot read properties of undefined (reading ‘send’)

I get this error when running the code, my research says its something about send not being available on it or not defined, I don’t fully understand it or how to fix it though.

The code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { Client, Collection, Intents, MessageEmbed } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS] })

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const channel = client.channels.cache.get('997960087249371136');

do {
  sleep(1000)
  let number = Math.floor(Math.random() * 5);
  
  if(number = 1) {

    channel.send("Carrier under attack!")
    
  } else if(number = 2) {

    channel.send("Carrier leak detected in lower quaters!")
    
  } else if(number = 3) {

    channel.send("All is quiet, for now.")
    
  } else if(number = 4) {

    channel.send("Unidentified aircraft entering our airspace!")
    
  } else {
    console.log("The impossible is possible!")
  } 
}
while(true);

I know the channels do exist.

Web Dev Server / Rollup doesn’t load CSS module using rollup-plugin-lit-css

I am having trouble importing CSS modules in my project.

I am using @web/dev-server along with @web/dev-server-rollup and @web/dev-server-storybook to host a Storybook page.

Here is my dev server config:

import {fromRollup} from '@web/dev-server-rollup';
import {storybookPlugin} from '@web/dev-server-storybook';

import rollupJson from '@rollup/plugin-json';
import rollupLitCss from 'rollup-plugin-lit-css';

const json = fromRollup(rollupJson);
const litCss = fromRollup(rollupLitCss);

export default {
  nodeResolve: {
    exportConditions: [
      'browser',
      'development'
    ],
    moduleDirectories: [
      'node_modules',
      'packages'
    ]
  },
  watch: true,
  mimeTypes: [
    '**/*.json',
    'js',
    'css'
  ],
  plugins: [
    json({}),
    litCss({}),
    storybookPlugin({type: 'web-components'})
  ],
  middleware: [
    async(ctx, next) => {
      await next();

      if(ctx.url.search('/node_modules/') > -1 && ctx.url.search('/@panama') === -1) {
        ctx.set('Cache-Control', 'public, max-age=604800, stale-while-revalidate=86400');
      }
    }
  ]
};

Here is my Storybook config:

const rollupJson = require('@rollup/plugin-json');
const rollupLitCss = require('rollup-plugin-lit-css');

module.exports = {
  stories: [
    '../packages/*/stories/*.stories.js'
  ],
  nodeResolve: {
    exportConditions: [
      'browser',
      'development'
    ]
  },
  rollupConfig(config) {
    config.plugins.push(rollupJson());
    config.plugins.push(rollupLitCss());

    return config;
  }
};

For any CSS import, Firefox logs an error and warning:

Loading module from “http://localhost:8000/packages/badge/src/Badge.css” was blocked because of a disallowed MIME type (“text/css”).

Loading failed for the module with source “http://localhost:8000/packages/badge/src/Badge.css”.

Creating a function that returns a function with individual letters [duplicate]

Trying to create a function that returns a function and returned function will provide the individual characters of the string passed to the original function on its invocations. When the end of the string is met, it will start back at the beginning.

Example: ‘cat’ should return: ‘c’ (on the first invocation) ‘a’ (on the second invocation) ‘t’ (on the third) ‘c’ (should then return back to beginning)

Here is the code that I have thus far:

function individualChar (str) {
let individualStr = str;
let invoked = 0;
return function () {
    if (invoked > 0) {
        let char = individualStr.slice(0);
        invoked++
        return `${char}`;
    }
    return individualStr;
}

}

My thought process was having the individualStr assigned to the str argument along with creating an ‘invoked’ counter. Then in the returned function, creating the ‘char’ variable and assigning that to the individualStr and slice it at the first character (0), to take it out, and then have an invoke counter to invoke the function as needed.

However, as of right now, it’s still only returning the entire string.

I thought about maybe using a while loop as well, to keep track of the number of invocations, but I wasn’t sure if that would be best approach for this.

Any guidance would be appreciated!

Uncaught Error in react component invalid hook, useSWR

using a useSWR wrapper and cannot the find issue that is causing the invalid hook error.

I went through https://reactjs.org/warnings/invalid-hook-call-warning.html and https://reactjs.org/docs/hooks-rules.html

I didnt have this problem before when using react context. After refactoring and switching to useSWR the error is new

error detail

react-dom.development.js:18687 The above error occurred in one of your React components:
...
line 115341
line 115342    e.default = function (n) {
line 115343        var e = n.title,
line 115344             t = void 0 !== e && e,
line 115345             a = n.subTitle,
    ...
    at e.default (http://localhost:3000/static/js/bundle.js:115343:15)
    at div
    at Player (http://localhost:3000/static/js/bundle.js:8314:108)
    at div
    at div
    at Tab (http://localhost:3000/static/js/bundle.js:6132:104)
    at Routes (http://localhost:3000/static/js/bundle.js:122353:5)
    at Router (http://localhost:3000/static/js/bundle.js:122286:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:121095:5)
    at SWRConfig$1 (http://localhost:3000/static/js/bundle.js:137530:21)
    at App (http://localhost:3000/static/js/bundle.js:2528:86)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

react-dom.development.js:12056  Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1476:1)
    at useRef (react.development.js:1515:1)
    at e.default (ReactNetflixPlayer.js:1:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)

here is the package.json

"dependencies": {
     "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-netflix-player": "^1.1.7",
    "react-redux": "^8.0.2",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^5.0.1",
    "redux": "^4.2.0",
    "swr": "^1.3.0"
},

here is the code

// useSharedState.js
---

import useSWR from 'swr'

export const useSharedState = (key, initial) => {
  const { data: state, mutate: setState } = useSWR(key, {
    fallbackData: initial,
  })

  return [state, setState]
}

// Player.js
---


import React, { useEffect, useContext } from 'react';
import ReactNetflixPlayer from "react-netflix-player";

const Player = () => {
const [playerItem, setPlayerItem] = useSharedState('playerContext')

 return (
      <React.Fragment>
      {playerItem && (
        <div id={"player"} >
          <ReactNetflixPlayer
          title={playerItem.title}
          backButton={() => { setPlayerItem(null) }}
          />
        </div>
        )}
        </React.Fragment>
    );
}
export default Player;


// Tab.js
---

import Player from "../Player"
...
function Tab() {

 return (
        ...
        <Player />
    <React.Fragment>...</React.Fragment>

);
}

export default Tab;

<Tab> is a component in <App>

thanks in advance

Editing array in json file using javascript

I have a file.json file which contains an array ["number1", "number2"] and I’m trying to add "number3" to that array using javascript. But if I define a variable in js file containing this array and try to edit it, only that variable will be edited, when I’m trying to edit the file itself! It sounds like a simple question, but for some reason I didn’t find the answer how to do it. Any help is appreciated!

react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of undefined

hello guys I’m quite new to react but this error is working outside an useEffect and an useState hook can someone please tell me whats the problem with my code which it cannot enter the useEffect loop and before that we face error however if I remove taskStructure:{ daysToBeCompleted, taskStatus, taskAuthor, taskModifier, dateCreated, dateModified }

everything will be fine and work correctly.


 import React, { useEffect, useState } from "react";
import { Grid , Stack, Box } from "@mui/material";
import "./tasks.style.css";



const Tasks = () => {
    const [ TaskConfig, setTaskConfig] = useState([]);
    
useEffect( () => {
    setTaskConfig(
        {
        _id:"01",
        taskTitle:"taskTitle",
        taskStructure:{
        taskDescription:"taskDescription",
        daysToBeCompleted:"daysToBeCompleted",
        taskStatus:"taskStatus",
        taskAuthor:"taskAuthor",
        dateCreated:"dateCreated",
        taskModifier:"taskModifier",
        dateModified:"dateModified"
        }}
)
},[])

const {  taskTitle,
taskDescription,
taskStructure:{
daysToBeCompleted,
taskStatus,
taskAuthor,
taskModifier,
dateCreated,
dateModified
}} = TaskConfig;

return(
<Box 
className="taskBox"
>
<Stack 
direction="column"
>
<Grid>  
{taskTitle} 
</Grid>
<Grid>
{taskDescription} {daysToBeCompleted} {taskStatus} 
</Grid>
<Grid>
{taskAuthor} {dateCreated} {taskModifier} {dateModified}
</Grid>

</Stack>
</Box>
);
}

export default Tasks;