context is not behaving properly in react

I created below context in react.

NameContext.tsx

import { createContext } from 'react';
export  const AppContext = createContext(""); 

I used this context inside my Layout.tsx . I am using inside Layout because I have some business logic to execute. based on that isActive value will be set.

const [isActive,setIsActive]=useState("NO");
return(
    <AppContext.Provider value={isActive}>
             <User/>
     </AppContext.Provider> 
)

now under User.tsx I am accessing this tab.

import { useContext } from "react";
import { Link } from "react-router-dom"
import { AppContext } from "../context/NameContext";

const User = ()=>{

 const context = useContext(AppContext);
  let isActive:any;

 if(context=="YES")
  isActive=true;

  else
  isActive=false;

  console.log("context is:"+context);
  console.log(isActive);
  
    return(
        <>
                  <span>
                 {isActive && <Link to="user" > List of Users</Link> } 
                  </span>

          </>        

    )
}
export default User;

in just one page refresh it is delivering values many times and most of the time default values. I dont want default values but the value which I set in provider.
how can I avoid this abnormal behaviour.

enter image description here

Algorithmic inclusion relation

I have an algorithmic problem where I used to have an array with an index and now I want to have all of them

Here’s an example
Left: The input array originally contained index relationships
Right: New array index contains relationships (results regardless of the number order)

enter image description here
[[2],[],1]

[[2],[3],1,[]]

[[2],[],1,1]

[[2],[],1,[0]]

Close the page after certain interval [Puppeteer]

I have used puppeteer for one of my projects to open webpages in headless chrome, do some actions and then close the page. These actions, however, are user dependent. I want to attach a lifetime to the page, where it closes automatically after, say 30 minutes, of opening irrespective of whether any action is performed or not.

I have tried setTimeout() functionality of Node JS but it didn’t work (or I just couldn’t figure how to make it work).

const puppeteer = require('puppeteer-core');

const browser = await puppeteer.connect({browserURL: browser_url});
const page = await browser.newPage();
// timer starts ticking here upon creation of new page (maybe in a subroutine and not block the main thread)

/**
 ..
 Do something
 ..
*/

// timer ends and closePage() is triggered.

const closePage = (page) => {
    if (!page.isClosed()) {
        page.close();
    }
}

Validation does not work when performing a custom validation, Express Validator Express

Using Express Validator I need to verify what comes in the request but I always get an error with Express Validator indicating “Invalid value“.

This is generated with this code in my route:

        check('detail').not().isEmpty()
        .custom( (value, {req}) => {
            console.log(req.body);
        }),

So I get the error:

error

I have tried with other routes to do the same thing, capture the request but I always get the same error message.

I appreciate your help.

How to auto click button on input field onchange in javascript

The button should be clicked automatically when amount is >0 and dropdown is selected

<html>
  <head>
    <script>
      document.getElementById("changeLanguage").onchange = function() {
        if (inputtxt.value.length == 0) {
          $('#bt').trigger('click');
        }
      };
    </script>
  </head>

  <body><label for="fname">Amount</label><input type="number" id="amt" name="amt"><select onchange="changeLanguage(this.value)">
      <option value="Choose" selected="selected">Choose</option<option value="IT">Italian</option>
      <option value="FR">France</option>
    </select><button type="button" id="bt">Click Me!</button></body>

</html>

I have tried using above code, but didn’t work.

Enter key in android keyboard also in android-webview not working for input in JavaScript

I have input type text in my html inside form tag. Key down event of JavaScript is not executing when I press enter key of mobile devices. In computer keyboard it’s working fine. When I put this input not inside form tag it’s working fine in mobile devices.
I tried keypress, key down, key up events.

$("body").on("keydown", "input, select, textarea, button", function(e) {
    var self = $(this),
        form = self.parents("form:eq(0)"),
        focusable,
        next,
        id;
    id = $(this).closest("tr").parent().parent().attr("id");


    if (
        e.keyCode == 13 ||
        e.keyCode == 9 ||
        e.key == "Next" ||
        e.key == "Go"
    ) {

        focusable = form
            .find('input[type!="checkbox"],a,select,button,textarea')
            .filter(":visible:not([readonly]):enabled");



        if (
            (this.type == "text" ||
                this.type == "tel" ||
                this.type == "email" ||
                this.type == "time" ||
                this.type == "select-one" ||
                this.type == "number" ||
                this.type == "date") &&
            $(this).attr("tabindex") < 700
        ) {

            previous_elem = $(this);
            valid_func_agets(this, e);
            return false;
        }
    }
})

Note:this inputs is under one div and am rewriting entire html when some events executes.

Issues with prompt and function

I have a page where a user is to input their email and password. Upon entering the information correctly, the user will click on the Submit button then see a prompt that asks if they are sure with proceeding, if the user types in “Yes”, the data in the email/password fields will be cleared. If they answer “No” then the information will still be there. I can’t seem to figure this out even though it seems very simple. Keep in mine please I am still a novice to HTML/Javascript.

Code for “Submit” button:

<button onclick="Submit()">Submit</button>

Code for function that decides whether the information is to be cleared or not:
function Submit() {

var ques = window.prompt("Are you sure?");
      if ((ques = "Yes")) {
        form.style.display = "none";
      } else {
      }
    }

How to add multiple values to an object ID later in mongodb

I am trying to add values inside the object id. Object id is created before but I want to add more values in the future inside the object ID.

This is my MongoDB database:

[{
        label: 'colors',
        options: [
            { label: 'Black', value: 1 },
            { label: 'Green', value: 2 },
        ]
    }]

My expectation is when I will send a new object it will insert a new object inside the options property. suppose my new object is {label: ‘blue’, value: 3} it will be like this:

[{
        label: 'colors',
        object: [
            { label: 'Black', value: 1 },
            { label: 'Green', value: 2 },
            {label: 'blue', value: 3} 
        ]
    },

I am trying this way, I am storing the previous data value, inserting a new value, and sending it to the backend. but it’s not working. is there any different way I can fix it?

  const addAttributeValues = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        if (label === '') {
            return
        }

        const slug = label?.split(' ').join('-')
        const options: any = [] // previous value storing 
        let update; // inserting previous and new value

        if (attr.options) {    // checking if the previous data has options property or not
            options.push(attr.options)
            const length: any = options.length
            update = { options: { ...options, [length]: { label, slug } }, id: attr._id }
        }

        else {     // if option property doesn't exist it means no new value added before 
            update = { options: { label, slug }, id: attr._id }
        }


        fetch('http://localhost:5000/dashboard/attributes', {
            method: 'PUT',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(update)
        })
            .then(res => res.json())
            .then(data => {
                setLabel('')
                setIfShouldUpdate(true)
            })

    }

Backend API, I use put method, I don’t know is there any other method for inserting new values in the future.

 // ADD ATTRIBUTES VALUE
        app.put('/dashboard/attributes/', async (req, res) => {
            const { options, id } = req.body
        
            const filter = { _id: objectId(id) }
    
            const updateDoc = {
                $set: {
                    options: options
                },
            };

            const result = await unityMartAttributes.updateOne(filter, updateDoc);
            res.json(result)
            console.log(result);
        })

How to access a data member or class in an included javascript in odoo?

I’m new to odoo, currently I’m trying to adding a data filter in account_report module, and it made me to modify the js file in odoo (which is I’m not well versed). I’ve tried to modify the source code js and it worked, but I didn’t allowed to modify the source code, so I had to inherit or override the js from a custom module. But I kept having trouble to access the data member or the class (I’m not really sure what it is) because part of my code need to declare that class/data member from the parent/included class, can u guys guide me how to access or get the class/data member? thanks in advance

here is my Code:

odoo.define('nrs_de_financial_report_currency.account_report', function (require) {
'use strict';
    var account_report = require('account_reports.account_report');
    var core = require('web.core');
    var datepicker = require('web.datepicker');
    var QWeb = core.qweb;
    var _t = core._t;

    account_report.include({
        unfold: function(line) {
            var self = this;            
            var parent_result = this._super.apply(this, arguments);
            var line_id = line.data('id');
            .
            .
            .
        render_searchview_buttons: function() {
            var self = this;
            // bind searchview buttons/filter to the correct actions
            var $datetimepickers = this.$searchview_buttons.find('.js_account_reports_datetimepicker');
            .
            .
            .
                   

                if (!_.isEmpty(fields)) {
                        //this is the trouble part, when I must declare the new M2MFilters
                        this.M2MFilters = new M2MFilters(this, fields);
                        this.M2MFilters.appendTo(this.$searchview_buttons.find('.js_account_partner_m2m'));
                    }
                } else {
                    this.$searchview_buttons.find('.js_account_partner_m2m').append(this.M2MFilters.$el);
                }

svelte-codejar “ctx[1] is not a constructor”

I am using svelte and svelte-codejar with prismjs and I am getting this error Uncaught TypeError: ctx[1] is not a constructor Here’s my code

<script context="module">
    import Prism from "prismjs"
      const highlight = (code, syntax) => Prism.highlight(code, Prism.languages[syntax], syntax);
    </script>
    
    <script>
      import "prismjs/themes/prism-tomorrow.css";
      import {getContext} from "svelte";
      import {DEFAULT_CODE_SAMPLE, DEFAULT_CODE_SYNTAX} from "./_sample";
      const store = getContext("CodeJar");
      const options = getContext("options");
      const CodeJar = $store;
      
    </script> 

any help would be great I also get Uncaught TypeError: $options is undefined if this line is added $: ({withLineNumbers = false} = $options);

Fake path after uploading file in next js – mysql

I am trying to upload file and store in Mysql DB

i can upload but when its stored in DB the link will be like this:

C:fakepathblank.pdf

am i doing something wrong?

here is my code:
Pages folder:

export default function AddShopForm() {



const [product, setProduct] = useState({
file: "",
});

const router = useRouter();
const handleChange = ({ target: { name, value } }) => {
setProduct({ ...product, [name]: value });
};

const handleSubmit = async (e) => {
e.preventDefault();
if (router.query.id) {
  await axios.put(`/api/shops/${router.query.id}`, product);
  router.push("/dashboard/shop");
} else {
  await axios.post("/api/shops", product);
  router.push("/dashboard/shop");
  swal("The shop has been added successfully");
}
};

useEffect(() => {
const getProductById = async () => {
  const { data } = await axios.get(`/api/shops/${router.query.id}`);
  setProduct(data);
};

if (router.query.id) {
  getProductById(router.query.id);
  console.log("pepeID");
}
}, [router.query.id]);
return (
<>

<div className="w-full max-w-xs">
  <form
    onSubmit={handleSubmit}
    className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"
    enctype="multipart/form-data"
  >
    

<label htmlFor="file">file</label>
<input
      type="file"
      name="file"
      onChange={handleChange}
      className="shadow border rounded py-2 px-3 text-gray-700"
      value={product.file}
    />

    <button className="bg-blue-500 hover:bg-blue-700 py-2 px-4 rounded focus:outline-none focus:shadow-outline font-bold text-white">
      Save file
    </button>
  </form>
</div>

);
}

API index:

import { pool } from "../../../config/db";
export default async function handler(req, res) {
const { method } = req;

switch (method) {
case "GET":
  return await getProdcuts(req, res);
case "POST":
  return await saveProduct(req, res);

default:
  break;
}
}

const saveProduct = async (req, res) => {
const { file } = req.body;
const [result] = await pool.query("INSERT INTO product SET ?", {
file 
});
console.log(result);
return res
.status(200)
.json({ file,
    id: result.insertId });
};

const getProdcuts = async (req, res) => {
const [result] = await pool.query("SELECT * FROM product;");
return res.status(200).json(result);
};

[id]:

import { pool } from "../../../config/db";

export default async function handler(req, res) {
switch (req.method) {
case "GET":
  return await getProdcutById(req, res);
case "DELETE":
  return await deleteProduct(req, res);
case "PUT":
  return await updateProduct(req, res);
default:
  break;
}
}

const getProdcutById = async (req, res) => {
const { id } = req.query;
const [result] = await pool.query("SELECT * FROM product WHERE id = ?", [id]);

return res.status(200).json(result[0]);
};

const deleteProduct = async (req, res) => {
const { id } = req.query;
const result = await pool.query("DELETE  FROM product WHERE id = ?", [id]);

return res.status(204).json();
};

const updateProduct = async (req, res) => {
const { id } = req.query;
const { file } = req.body;

//*Para Actualizar tengo que enviar dos cosas, el id y el body
try {
await pool.query(
  "UPDATE product SET business_type= ?, shop_name = ?,company_register_name = ? WHERE id = ?",
  [file , id]
);
return res.status(204).json();
} catch (error) {
console.log(error.message);
}
};

i was able to store other kind of data in db without any problem but whenever i upload a file i will get Fakepath

i am new to nextjs and still learning, i searched online but still wasn’t able to find an answer

Can’t access data from miragejs and redux

It’s the first time i use miragejs and maybe i did something wrong,but in console i get my data which i need to be in a sort of time line dynamically. I created the redux slice,async thunk,and when i try to access the state i get get this erro in console TypeError: Cannot read properties of undefined (reading ‘educationList’) And the app doesnt work. If i put the data as a prop from component,it works,but with redux thunk it doesnt.. Could you tell me what i’m doing wrong please?
Here is my mirage server:

import { createServer,Model } from "miragejs"

export const makeServer =({ environment = 'test' } = {})  => {
    let server = createServer({
      environment,
        models: {
          educations: Model,
         skills:Model
        },

        seeds(server) {
            server.create("education", { date: 2001, title: "Title 0", text: "Elit voluptate ad nostrud laboris. Elit incididunt mollit enim enim id id laboris dolore et et mollit. Mollit adipisicing ullamco exercitation ullamco proident aute enim nisi. Dolore eu fugiat consectetur nulla sunt Lorem ex ad. Anim eiusmod do tempor fugiat minim do aliqua amet ex dolore velit.rn" });
            server.create("education", { date: 2000, title: "Title 1", text: "Et irure culpa ad proident labore excepteur elit dolore. Quis commodo elit culpa eiusmod dolor proident non commodo excepteur aute duis duis eu fugiat. Eu duis occaecat nulla eiusmod non esse cillum est aute elit amet cillum commodo.rn" });
            server.create("education", { date: 2012, title: "Title 2", text: "Labore esse tempor nisi non mollit enim elit ullamco veniam elit duis nostrud. Enim pariatur ullamco dolor eu sunt ad velit aute eiusmod aliquip voluptate. Velit magna labore eiusmod eiusmod labore amet eiusmod. In duis eiusmod commodo duis. Exercitation Lorem sint do aliquip veniam duis elit quis culpa irure quis nulla. Reprehenderit fugiat amet sint commodo ex.rn" });
          },
    
        routes() {
            //this.namespace = 'api/educations';
            this.get('api/educations', (schema, request) => {
              return schema.educations.all();
            });

            // this.namespace = 'api/skills';
            this.get('api/skills', (schema, request) => {
              return schema.skills.all();
            });
    

          this.post('api/skills', (schema, request) => {
            let attrs = JSON.parse(request.requestBody);
            return schema.skills.create(attrs);
          });
        },
      })
      return server;
    }  

redux store:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import { postSlice } from '../features/education/educationSlice';

const rootReducer = combineReducers({
    visibilityState: toggleButtonReducer,
    educationState: postSlice,
})

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))

export const persistor = persistStore(store)

educationSlice :

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
    educationList: []
}


export const getEducation = createAsyncThunk(
    'educations/getEducations',
    async (_, { rejectWithValue, dispatch }) => {
        const res = await axios.get('api/educations')
        dispatch(setEducations(res.data))
        console.log(res.data)
    })


export const postSlice = createSlice({
    name: 'educations',
    initialState,
    reducers: {
        setEducations: (state, action) => {
            state.educationList = action.payload
        },
    },
    extraReducers:{
        [getEducation.fulfilled]:()=> console.log('fullfiled'),
        [getEducation.pending]:()=>console.log('fullfiled'),
        [getEducation.rejected]:() =>console.log('rejected'),
    },
})

export const {setEducations} = postSlice.actions
export default postSlice.reducer;

And the component were i need data:

import '../../assets/styles/css/TimeLine/base.css'
import { useDispatch } from 'react-redux'
import { getEducation } from '../../features/education/educationSlice'
import { store } from '../../store'
import { useSelector } from 'react-redux'

const TimeLine = () => {

const dispatch = useDispatch()
dispatch(getEducation())
const data = useSelector(state => state.educationState.educationList)

    return (
        <>
            <section id='timeLine'>
                <h1 className='educationSection'>Education</h1>
                <div id="timeline" className='timelineWrapper'>
                    {data.map((info) => (
                        <div className="timeline-item" key={info.id}>
                            <span className="timeline-icon">
                                <span>&nbsp;&nbsp;</span>
                                <span className="year">{info.date}</span>
                            </span>
                            <div className='timeline-content'>
                                <h2>{info.title}</h2>
                                <p>{info.text}</p>
                            </div>
                        </div>
                    ))}
                </div>
            </section>
        </>
    )
}

export default TimeLine  

This is what i have in console:
enter image description here

but can’t acces the data.. please help,i’m stuck.. thanks in advance!

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately.

<noscript> this page is wrong </noscript>

If you disable JavaScript in developer tools and go to another page, noscript is applied.
I want the noscript content to be applied immediately when JavaScript is disabled, but is there any way?

Or is there anything else I can do to disable javascript mode?