Get locally instanced ‘this’ for native code prototypes [duplicate]

I’m trying to extend a built-in javascript function via prototype, but when I attempt to refer to this, Window is returned. Given that I don’t really have access to rewrite the implementation, are there any ways to get around this?

Specifically I’m trying to extend URLSearchParams in such a way that it unsets values properly. Something like:

URLSearchParams.prototype.setOrUnset = (key, val) => {
    if(val){
        this.set(key, val)
    } else {
        this.delete(key)
    }
}

how to check after deleting one element from array

hello i have creating a pragam that delete one array from another but. And it works fine i think but if i put 2 same value simultaneously, it remove only one value because of second argument of splice function. How can i check after deleting a element again if there any other number left my code is below.

const arr1 = [1, 2, 2, 3, 5, 2, 3, 7];
const arr2 = [2, 3];

let countArr = [];
for (let i = 0; i < arr2.length; i++) {
  for (let j = 0; j <= arr1.length; j++) {
    if (arr1[j] === arr2[i]) {
      arr1.splice(j, 1);
    }
  }
}
console.log(arr1);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script src="demo.js"></script>
</body>

</html>

Moving my Node.js app to Express, getting Document Null errors

I have my fully working app here that I’m trying to host on a localhost server using Express.js

https://jsfiddle.net/mostafa91/6axesy2t/2/

Here is my server.js that I run with “node server.js”:

const express = require('express');
const app = express();
const port = 2525;

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/Gameboard.html');
});

app.listen(port, () => {
    console.log(`Tic-Tac-Toe listening at http://localhost:${port}`);
});

app.use(express.static('public'));

I keep getting errors when I try to play the game (vs. Players option):

Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at setBoardHoverClass (Gameboard.js:74)
    at startGame (Gameboard.js:32)
    at Gameboard.js:20

I’ve included my file structure as well: Here

Vanilla JS getting all links under span using XPath and foreach loop

Het all I can not seem to get this below code to work:

var links = doc.DocumentNode.SelectSingleNode("/html/body/div[1]/div/div[4]/div/div/div[2]/div[2]/span[1]");

foreach (HtmlNode item in table.SelectNodes("//span[1]/descendant::a[starts-with(@href,'/photo')]"))
{
    console.log("test");
}

It keeps telling me:

Uncaught SyntaxError: missing ) after argument list

It looks like all my “)” are present and in the correct spots?

the HTML that I am getting the links from looks like this:

<span>
  <a href="/photo356.png" class="_4dvp" id="_D9">
    <div class="_403j">
      <i class="im_2sxw" style="width:100px;height:100px;" aria-label="pic" role="img"></i>
      <div class="_5fef">
        <div class="_5feg" role="link" aria-label="25">
          <i class="imgMGdk7"></i>25
        </div>
        <div class="fezg" role="link" aria-label="15">
          <i class="_imgsp_l0"></i>15
        </div>
      </div>
    </div>
  </a>
  <a href="/photo17814561.png" class="_39pvp" id="u3_sz">
    <div class="_403j">
      <i class="imgxw" style="width:100px;height:100px;" aria-label="pic61" role="img"></i>
      <div class="_5f">
        <div class="fzeg" role="link" aria-label="23">
          <i class="_img2e1b6"></i>23
        </div>
    ...etc....

the XPath starts at the . The XPath is this:

/html/body/div[1]/div/div[4]/div/div/div[2]/div[2]/span[1]

But like I said above I just get that JS error. I’m not even sure my XPATH logic is even correct since I’m not able to pass this error and continue on…

Help would be great!

How do I get a js library without import

I want to make a js library, and I have all the code. Libraries like Jquery can let you do like

<script src = "..."></script>
<script>
//uses the library
</script>

without the import * from JQuery.
How can I do this without declaring the library a modular or importing?

Remove an HTML tag from Div [closed]

I use a WYSIWYG editor in my website. It has the option of changing the font-size and fontcolor of the chapter.

However, I want to make sure that if the user desires, they can actually override the font settings while reading it.

I know I can just get the innerHTML and replace the font-size and color attributes from it. However, it may be possible that font-size and color may actually be part of the text instead of HTML tag.

So how can I remove these attributes from HTML without affecting the main text?

How to dynamically add a changeable size canvass to pdf?

I am using Html2Canvas and jsPDF to create a canvass from a hidden div content, the core issue here is when I want to mount the canvass on the pdf,

what I am considering is, the items div could have 1 item and could have 1000, what I want to implement is the more items the smaller the items get on the canvass so they will always fit no matter how big or how small, any idea how to solve this? , another case here is how to create another pdf page if items don’t fit on a single page in case my previous question is impossible to implement.

const html2canvasfn = () => {
    html2canvas(
      document.getElementById('clone')!,
      {
        onclone: function (clonedDoc) {
          clonedDoc.getElementById('clone')!.style.display = 'flex';
        },
      }

    ).then((canvas) => {
      document.getElementById('clone')!.style.display = 'none';
      
      const imgData = canvas.toDataURL('image/png');
      // A4 size
      var doc = new jsPDF('p', 'mm', 'a4');
      
      var width = doc.internal.pageSize.getWidth();
      var height = doc.internal.pageSize.getHeight();
      let w = document.querySelector('#clone')!.scrollWidth;
      let h = document.querySelector('#clone')!.scrollHeight;
      
      doc.addImage(imgData, 'PNG', 30, 0, /*w!*/ /*1500 / 10*/ w! /*width*/ /*w!*/, /*height*/ /*h!*/ h!);
      doc.save('doc.pdf');
  
    });
  };

return (
<div style={{ textAlign: 'center' }}>
<Container id='clone' style={{ display: 'none', flexDirection: 'column', justifyContent:                'center', textAlign: 'center', minWidth: 900 }}>
{Object.entries(groupItems(context.exercises[mContext.modal.id])).map(([groupName, items]:             Mapped, i) => (
<div>
<ul>
{i + 1}
{Icons[groupName]}
{groupName}
</ul>
{items.map((el) => (
<li
el.text
/>
))}

</div>
))}
</Container>
</div>
  );
};

Importing “@daily-co/daily-js” into SvelteKit app throws “global is not defined” error

What I tried:

  1. I tried work around it via if (browser), more specifically{
    if (!browser) { let DailyIframe = await import('daily-co/daily-js) } in the load function inside <script context="module"> ) so the code is always executed on the server). Then pass it as a prop to a component. However, although it worked on the server, the local dev environment re-runs the load function (which has to return an empty prop as it never imported anything) and overrides DailyIframe’s value (might be a bug with Vite/SvelteKit).

  2. I tried to import the library in an end-point e.g. api.json.js instead, which is always executed on the server. However, it has to return a json, and I can’t pass an entire library variable onto it.

After research
It seems like a combination of problems from Vite, SvelteKit and certain libraries where global is undefined: SvelteKit With MongoDB ReferenceError: global is not defined)

But I cannot use his solution of putting it in an endpoint, because I need the DailyIframe and the mic audio stream from the client to create a video conference room

Also, why would certain libraries Daily (and looking at other related Stackoverflow posts, MongoDB) throw this error in the first place, while other libraries are safe to use?

Anyway suggestion is appreciated!

change button icon Bootstrap 5 without jquerry

I’m trying to change the button’s icon and text onclick in a project (node js, javascript) using Bootstrap 5 (without jquery).
There are dozens of example of it, all using jquery with older versions of Bootstrap. Is there a way to do it in latest Bootstrap (without jquery)?

cant get setSelectionRange to put the cursor at the beginning of the input

Hi,

I have this code:

inputform.addEventListener('keypress', function(e) {
 const tgt = e.target;
 
 if (tgt.id==="usermsg") {
  if (e.which == 13 && !e.shiftKey && tgt.value) {
    tgt.value = '';
    tgt.setSelectionRange(0,0);
  }
 }
});

as you hit ENTER its supposed to clear the textarea input and return the cursor to the start but it wont do it. Instead, the cursor stays at the second line. Here is the fiddle: https://jsfiddle.net/xbc0vong/

why is that?

Thank you.

JavaScript Not Automatically Deleting Variable After Instructed

I made a script that creates an HTML tag using JavaScript. I declared a variable called tag, specifically knowing you can’t delete() let and var variables, but it won’t automatically delete it in my code:


function(tagType, attr1 = null, value1 = null, attr2 = null, value2 = null, attr3 = null, value3 = null, attr4 = null, value4 = null, attr5 = null, value5 = null, attr6 = null, value6 = null, attr7 = null, value7 = null, attr8 = null, value8 = null, attr9 = null, value9 = null, attr10 = null, value10 = null) {
  tag = document.createElement(tagType);
  if (attr1 != null) {
    tag.setAttribute(attr1, value1)
  };
  if (attr2 != null) {
    tag.setAttribute(attr2, value2)
  };
  if (attr3 != null) {
    tag.setAttribute(attr3, value3)
  };
  if (attr4 != null) {
    tag.setAttribute(attr4, value4)
  };
  if (attr5 != null) {
    tag.setAttribute(attr5, value5)
  };
  if (attr6 != null) {
    tag.setAttribute(attr6, value6)
  };
  if (attr7 != null) {
    tag.setAttribute(attr7, value7)
  };
  if (attr8 != null) {
    tag.setAttribute(attr8, value8)
  };
  if (attr9 != null) {
    tag.setAttribute(attr9, value9)
  };
  if (attr10 != null) {
    tag.setAttribute(attr10, value10)
  };
  document.getElementsByTagName('head')[0].appendChild(tag);
  if (tag) {
    delete(this.tag);
  }
},

In the end of the code, I said delete(tag), and it didn’t work. So then I tried checking if variable named tag was there. if(tag) { delete(tag) }.

Why isn’t it automatically deleting the variable? If I just type delete(tag) into the console, it will delete it.

Thank you for your help!

Error: Objects are not valid as a React child (but I’m not rendering any object)

I’m trying to retrieve a list of prisons which has a nested object address. It is structured like this:

  { uuid,
    address: {
      city,
      country,
      state,
      street,
      zip },
    prisonName,
    rules,
}

For the sake of simplicity all other objects are strings for now.

I’m getting the error “Error: Objects are not valid as a React child (found: object with keys {city, zip, state, country, street}). If you meant to render a collection of children, use an array instead.” but I’ve poured over my code a dozen times, I know I can’t render Address, it’s an object, not a string, but I don’t render it. I render properties of it, but never the whole object.

I even commented out any instances where I was console.logging the address just to be on the safe side.

prisons.js

import * as ActionTypes from './types'
import PrisonDataService  from '../services/prison.service'

export const createPrison = (prisonName, address, rules) => async (dispatch) => {
    try {
        const res = await PrisonDataService.create({ prisonName, address, rules })
        dispatch({
            type: ActionTypes.CREATE_PRISON,
            payload: res.data,
        });
        return Promise.resolve(res.data);
    } catch (err) {
        return Promise.reject(err)
    }
};

export const retrievePrisons = () => async (dispatch) => {
    try {
        const res = await PrisonDataService.getAll();
        dispatch({ //This is where the compiler says the error is
            type: ActionTypes.RETRIEVE_PRISONS,
            payload: res.data,
        });
    } catch (err) {
        console.log(err)
    }
};

export const updatePrison = (id, data) => async (dispatch) => {
    try {
      const res = await PrisonDataService.update(id, data);
  
      dispatch({
        type: ActionTypes.UPDATE_PRISON,
        payload: data,
      });
  
      return Promise.resolve(res.data);
    } catch (err) {
      return Promise.reject(err);
    }
  };
  
  export const deletePrison = (id) => async (dispatch) => {
    try {
      await PrisonDataService.delete(id);
  
      dispatch({
        type: ActionTypes.DELETE_PRISON,
        payload: { id },
      });
    } catch (err) {
      console.log(err);
    }
  };
  
  export const deleteAllPrisons = () => async (dispatch) => {
    try {
      const res = await PrisonDataService.deleteAll();
  
      dispatch({
        type: ActionTypes.DELETE_ALL_PRISONS,
        payload: res.data,
      });
  
      return Promise.resolve(res.data);
    } catch (err) {
      return Promise.reject(err);
    }
  };
  
  export const findPrisonByName = (name) => async (dispatch) => {
    try {
      const res = await PrisonDataService.findByName(name);
  
      dispatch({
        type: ActionTypes.RETRIEVE_PRISONS,
        payload: res.data,
      });
    } catch (err) {
      console.log(err);
    }
  };

prison-list.component.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { Button, Col, Input, InputGroup, Label, List, ListGroup } from "reactstrap";
import { retrievePrisons, findPrisonByName, deleteAllPrisons } from "../../actions/prisons";
import AddPrison from "./add-prison.component"

class PrisonsList extends Component {
  constructor(props) {
    super(props);
    this.onChangeSearchName = this.onChangeSearchName.bind(this);
    this.refreshData = this.refreshData.bind(this);
    this.setActivePrison = this.setActivePrison.bind(this);
    this.findByName = this.findByName.bind(this);
    this.removeAllPrisons = this.removeAllPrisons.bind(this);

    this.state = {
      currentPrison: null,
      currentIndex: -1,
      searchName: " ",
    };
  }

  componentDidMount() {
    this.props.retrievePrisons();
  }

  onChangeSearchName(e) {
    const searchName = e.target.value;

    this.setState({
      searchName: searchName,
    });
  }

  refreshData() {
    this.setState({
      currentPrison: null,
      currentIndex: -1,
    });
  }

  setActivePrison(prison, index) {
    console.log(prison)
    this.setState({
      currentPrison: prison,
      currentIndex: index,
    });
  }

  removeAllPrisons() {
    this.props
      .deleteAllPrisons()
      .then((response) => {
        console.log(response);
        this.refreshData();
      })
      .catch((e) => {
        console.log(e);
      });
  }

  findByName() {
    this.refreshData();
    this.props.findPrisonByName(this.state.searchName);
  }

  render() {
    const { searchName, currentPrison, currentIndex } = this.state;
    const { prisons } = this.props;

    console.log(prisons)

    return (
        <List className="row">
        <Col md="8">
          <InputGroup className="mb-3">
            <Input
              type="text"
              className="form-control"
              placeholder="Search by name"
              value={searchName}
              onChange={this.onChangeSearchName}
            />
            <div className="input-group-append">
              <Button
                outline
                color="secondary"
                onClick={this.findByName}
              >
                Search
              </Button>
            </div>
          </InputGroup>
        </Col>
        <div className="col-md-6">
          <h4>Prison List</h4>

          <ListGroup>
            {prisons &&
              prisons.map((prison, index) => (
                <li
                  className={
                    "list-group-item " +
                    (index === currentIndex ? "active" : "")
                  }
                  onClick={() => this.setActivePrison(prison, index)}
                  key={index}
                >
                  {prison.prisonName}
                </li>
              ))}
          </ListGroup>

          <Button
            color="danger"
            className="m-3"
            onClick={this.removeAllPrisons}
          >
            Remove All
          </Button>
        </div>
        <Col md={6}>
          {currentPrison ? (
            <div>
              <h4>Prison</h4>
              <div>
                <Label>
                  <strong>Prison Name:</strong>
                </Label>{" "}
                {currentPrison.prisonName}
              </div>
              <div>
                <Label>
                  <strong>Address:</strong>
                </Label>{" "}
                {currentPrison.address.street}
              </div>
              {/* {console.log(currentPrison.address)} */}
              <div>
                <Label>
                  <strong>UUID:</strong>
                </Label>{" "}
                {currentPrison.uuid}
              </div>
              <div>
                <Label>
                  <strong>Inmates:</strong>
                </Label>{" "}
                {currentPrison.inmates}
              </div>
                <Link
                to={"/prison/" + currentPrison.uuid}
              >
                Edit
              </Link>
            </div>
          ) : (
            <div>
              <br />
              <p>Please click on a Prison...</p>
            </div>
          )}
        </Col>
        <h1>Add Prison</h1>
        <AddPrison/>
      </List>    );
  }
}

const mapStateToProps = (state) => {
  return {
    prisons: state.prisons,
  };
};

export default connect(mapStateToProps, { retrievePrisons, findPrisonByName, deleteAllPrisons })(PrisonsList);

prison.component.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { updatePrison, deletePrison } from "../../actions/prisons";
import PrisonDataService from "../../services/prison.service";
import { Button, Form, FormGroup, Input, Label } from "reactstrap"

class Prison extends Component {
  constructor(props) {
    super(props);
    this.onChangePrisonName = this.onChangePrisonName.bind(this);
    this.onChangeCity = this.onChangeCity.bind(this);
    this.onChangeCountry = this.onChangeCountry.bind(this);
    this.onChangeState = this.onChangeState.bind(this);
    this.onChangeStreet = this.onChangeStreet.bind(this);
    this.onChangeZip = this.onChangeZip.bind(this);
    this.onChangeRules = this.onChangeRules.bind(this);
    this.getPrison = this.getPrison.bind(this);
    this.updateStatus = this.updateStatus.bind(this);
    this.updateContent = this.updateContent.bind(this);
    this.removePrison = this.removePrison.bind(this);

    this.state = {
      currentPrison: {
        uuid: null,
        prisonName: " ",
        address: { 
            city: " ",
            country: " ",
            state: " ",
            street: " ",
            zip: " "
        },
        rules: " "
      },
      message: " ",
    };
  }

  componentDidMount() {
    console.log(this.props)
    this.getPrison(this.props.match && this.props.match.params.uuid);
  }

  onChangePrisonName(e) {
    const prisonName = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          prisonName: prisonName,
        },
      };
    });
  }

  onChangeCity(e) {
    var newAddress = {...this.state.currentPrison.address}
    address.city = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          address: newAddress,
        },
      };
    });
  }

  onChangeCountry(e) {
    var newAddress = {...this.state.currentPrison.address}
    address.country = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          address: newAddress,
        },
      };
    });
  }

  onChangeState(e) {
    var newAddress = {...this.state.currentPrison.address}
    address.state = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          address: newAddress,
        },
      };
    });
  }

  onChangeStreet(e) {
    var newAddress = {...this.state.currentPrison.address}
    address.street = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          address: newAddress,
        },
      };
    });
  }

  onChangeZip(e) {
    var newAddress = {...this.state.currentPrison.address}
    address.zip = e.target.value;

    this.setState(function (prevState) {
      return {
        currentPrison: {
          ...prevState.currentPrison,
          address: newAddress,
        },
      };
    });
  }

  onChangeRules(e) {
    const rules = e.target.value;

    this.setState((prevState) => ({
      currentPrison: {
        ...prevState.currentPrison,
        rules: rules,
      },
    }));
  }

  getPrison(uuid) {
    PrisonDataService.get(uuid)
      .then((response) => {
        this.setState({
          currentPrison: response.data,
        });
        console.log(response.data);
      })
      .catch((e) => {
        console.log(e);
      });
  }

  updateStatus(status) {
    var address = {
      street: this.state.currentPrison.address.street,
      state: this.state.currentPrison.address.state,
      country: this.state.currentPrison.address.country,
      city: this.state.currentPrison.address.city,
      zip: this.state.currentPrison.address.zip
    }
    var data = {
      uuid: this.state.currentPrison.uuid,
      prisonName: this.state.currentPrison.prisonName,
      address: address,
      rules: this.state.currentPrison.rules,
    };

    this.props
      .updatePrison(this.state.currentPrison.uuid, data)
      .then((response) => {
        this.setState((prevState) => ({
          currentPrison: {
            ...prevState.currentPrison,
          },
        }));

        this.setState({ message: "The status was updated successfully!" });
      })
      .catch((e) => {
        console.log(e);
      });
  }

  updateContent() {
    this.props
      .updatePrison(this.state.currentPrison.uuid, this.state.currentPrison)
      .then((response) => {
        console.log(response);
        this.setState({ message: "The prison was updated successfully!" });
      })
      .catch((e) => {
        console.log(e);
      });
  }

  removePrison() {
    this.props
      .deletePrison(this.state.currentPrison.uuid)
      .then(() => {
        this.props.history.push("/prisons");
      })
      .catch((e) => {
        console.log(e);
      });
  }

  render() {
    const { currentPrison } = this.state;

    return (
      <div>
      {currentPrison ? (
        <div className="edit-form">
          <h4>Prison</h4>
          <Form>
            <FormGroup>
              <Label htmlFor="prisonName">Prison Name</Label>
              <Input
                type="text"
                className="form-control"
                id="prisonName"
                value={currentPrison.prisonName}
                onChange={this.onChangePrisonName}
              />
            </FormGroup>
            {/* {console.log(currentPrison.address)} */}
            {/* <FormGroup>
              <Label htmlFor="city">City</Label>
              <Input
                type="text"
                className="form-control"
                id="city"
                value={currentPrison.address.city}
                onChange={this.onChangeCity}
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="country">Country</Label>
              <Input
                type="text"
                className="form-control"
                id="country"
                value={currentPrison.address.country}
                onChange={this.onChangeCountry}
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="state">State</Label>
              <Input
                type="text"
                className="form-control"
                id="state"
                value={currentPrison.address.state}
                onChange={this.onChangeState}
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="street">Street</Label>
              <Input
                type="text"
                className="form-control"
                id="street"
                value={currentPrison.address.street}
                onChange={this.onChangeStreet}
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="zip">Zip</Label>
              <Input
                type="text"
                className="form-control"
                id="zip"
                value={currentPrison.address.zip}
                onChange={this.onChangeZip}
              />
            </FormGroup> */}
            <FormGroup>
              <Label for="rules">Rules</Label>
              <Input
                type="text"
                className="form-control"
                id="rules"
                value={currentPrison.rules}
                onChange={this.onChangeRules}
              />
            </FormGroup>
          </Form>

          <Button
          color="danger"
          onClick={this.removePrison}
          >
            Delete
          </Button>

          <Button
            type="submit"
            color="primary"
            onClick={this.updateContent}
          >
            Update
          </Button>
          <p>{this.state.message}</p>
        </div>
      ) : (
        <div>
          <br />
          <p>Please click on a Prison...</p>
        </div>
      )}
    </div>
    );
  }
}

export default connect(null, { updatePrison, deletePrison })(Prison);

add-prison.component.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { Button, FormGroup, Label, Input } from "reactstrap";
import { createPrison } from "../../actions/prisons";

class AddPrison extends Component {
  constructor(props) {
    super(props);
    this.onChangeCity = this.onChangeCity.bind(this);
    this.onChangeCountry = this.onChangeCountry.bind(this);
    this.onChangeState = this.onChangeState.bind(this);
    this.onChangeStreet = this.onChangeStreet.bind(this);
    this.onChangeZip = this.onChangeZip.bind(this);
    this.onChangePrisonName = this.onChangePrisonName.bind(this);
    this.onChangeRules = this.onChangeRules.bind(this);
    this.savePrison = this.savePrison.bind(this);
    this.newPrison = this.newPrison.bind(this);

    this.state = {
      uuid: null,
      address: {
        city: " ",
        country: " ",
        state: " ",
        street: " ",
        zip: " ",
      },
      prisonName: " ",
      rules: " ",
    };
  }

  onChangeCity(e) {
    var newAddress = { ...this.state.address }
    newAddress.city = e.target.value
    this.setState({
      address: newAddress,
    });
  }
    
  onChangeCountry(e) {
    var newAddress = { ...this.state.address }
    newAddress.country = e.target.value
    this.setState({
      address: newAddress,
    });
  }

  onChangeState(e) {
    var newAddress = { ...this.state.address }
    newAddress.state = e.target.value
    this.setState({
      address: newAddress,
    });
  }

  onChangeStreet(e) {
    var newAddress = { ...this.state.address }
    newAddress.street = e.target.value
    this.setState({
      address: newAddress,
    });
  }

  onChangeZip(e) {
    var newAddress = { ...this.state.address }
    newAddress.zip = e.target.value
    this.setState({
      address: newAddress,
    });
  }

  onChangeRules(e) {
    console.log(e.target.value)
    this.setState({
      rules: e.target.value,
    })
  }

  onChangePrisonName(e) {
    console.log(e.target.value)
    this.setState({
      prisonName: e.target.value
    })
  }

  savePrison() {
    const { prisonName, address, rules } = this.state;
    console.log(address)
    this.props
      .createPrison(prisonName, address, rules)
      .then((data) => {
        this.setState({
          prisonName: data.prisonName,
          address: data.address,
          rules: data.rules,
        });
        console.log(data);
      })
      .catch((e) => {
        console.log(e);
      });
  }

  newPrison() {
    this.setState ({
      uuid: null,
      address: {
        city: " ",
        country: " ",
        state: " ",
        street: " ",
        zip: " ",
      },
      prisonName: " ",
      rules: "",
    });
  }

  render() {
    return (
      <div className="submit-form">
        {this.state.submitted ? (
          <div>
            <h4>You submitted successfully!</h4>
            <Button color="success" onClick={this.newPrison}>
              Add
            </Button>
          </div>
        ) : (
          <div>
            <FormGroup>
              <Label htmlFor="prisonName">Prison Name</Label>
              <Input
                type="text"
                className="form-control"
                id="prisonName"
                required
                value={this.state.prisonName}
                onChange={this.onChangePrisonName}
                name="prisonName"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="city">City</Label>
              <Input
                type="text"
                className="form-control"
                id="city"
                required
                value={this.state.address.city}
                onChange={this.onChangeCity}
                name="city"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="country">Country</Label>
              <Input
                type="text"
                className="form-control"
                id="country"
                required
                value={this.state.address.country}
                onChange={this.onChangeCountry}
                name="prison"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="state">State</Label>
              <Input
                type="text"
                className="form-control"
                id="state"
                required
                value={this.state.address.state}
                onChange={this.onChangeState}
                name="state"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="street">Street</Label>
              <Input
                type="text"
                className="form-control"
                id="street"
                required
                value={this.state.address.street}
                onChange={this.onChangeStreet}
                name="releaseDate"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="zip">Zip</Label>
              <Input
                type="text"
                className="form-control"
                id="zip"
                required
                value={this.state.address.zip}
                onChange={this.onChangeZip}
                name="releaseDate"
              />
            </FormGroup>
            <FormGroup>
              <Label htmlFor="rules">Rules</Label>
              <Input
                type="text"
                className="form-control"
                id="rules"
                required
                value={this.state.rules}
                onChange={this.onChangeRules}
                name="rules"
              />
            </FormGroup>

            <Button onClick={this.savePrison} color="success">
              Submit
            </Button>
          </div>
        )}
      </div>
    );
  }
}

export default connect(null, { createPrison })(AddPrison);

Keep getting an uncaught typeError when attempting addEventListener [duplicate]

Another rookie issue im having guys. I assumed all my syntax was correct and all functions, variables and etc has been declared, but everytime i run the script i get this:

—-> Afri-culture.js:16

   Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') <---

I have tried a few different solutions, but still keep getting the same issue, not really sure whats going on at all.
Can anyone here please lead me to the right direction. Here is the code from earlier:

const x = document.querySelector('x')
const overlay = document.querySelector('overlay')
const modal = document.querySelector('modal')

    const openOverlay = function() {
        modal.classList.remove('hidden');
        overlay.classList.remove('hidden');
    }
    
    const closeOverlay = function() {
        modal.classList.add('hidden');
        overlay.classList.add('hidden');
    }

    pop.addEventListener('click', openOverlay, false);
x.addEventListener('click', closeOverlay, false);
overlay.addEventListener('click', closeOverlay, false);


.pop {
    padding: 10px 15px;
    background: #4e8b8f;
    border: none;
    border-radius: 1.2px;
    font-family: Impact;
    color: black;
    margin-top: 10px;
    cursor: pointer;
}

.modal {
    background-color: #4e8b8f;
    border-radius: 1.3px;
    padding: 1rem;
    width: 15rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 6;
    font-family: Impact;
}

.x {
    position: absolute;
    top: 0;
    right: 0;
    background-color: transparent;
    border: none;
    border-radius: 1px;
    color:red;
    font-size: 10px;
    cursor: pointer;
}

.overlay {
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(3px);
    border-radius: 2px;
    height: 100%;
    width: 100%;
    z-index: 5; 
}

.hidden {
    display: none;
} 

<!DOCTYPE html>
<html>

<!-----tab header---------------->

    <head>
        <title>Jalloh Web Construction Home</title>
        <link href=Afri-culture.css rel="stylesheet">
        <link rel="shortcut icon" type="image/jpg" href="jalloh white.jpg">
        <meta charset="utf-8" />
        </head>

        <header name="container">

            <!-----nav bar------>

            <div class="container">
              <img id="clarkweb" src="jalloh.jpg" alt="jalloh web construction">

                <nav>
                    <ul>
                     <!-----  <li><a href="https://www.etsy.com/shop/EastAmbienceLLC?ref=seller-platform-mcnav">Home</a></li>----->
                        <li><a href="https://www.linkedin.com/in/geedo-jalloh/">About Me</a></li>
                        <li><a href="#">My Hobbies</a></li>
                        <li><a href="#">Contact Me</a></li>
                    </ul>
                </nav>
            </div>
           
        </header>
        <h1>Welcome To My Portfolio</h1>
        <button class="pop">Enter</button>
        <div class="modal hidden">
    <br>
    <script src="Afri-culture.js"></script>
    <button class="x">x</button>
    <img src="smokegif.gif" id="smoke" alt="cyber smoke">
    <h3>Under Construction</h3>
                </div>
                <div class="overlay hidden"></div>
           
  
    
  

        <body id=body>
            <br>
               </body>
               
                               
    </div>
</div>
            </div>
            <hr>
            
    <div class="container2"> 
        <footer>
            <a href="https://twitter.com/GeedoJalloh"><img id="clarktwo" src="jalloh white.jpg" alt="clark web"></a>
        </footer> 
               
    </div> 
</html>```

need Mongoose Model.find() to work when queries aren’t present

I’m currently working on the freeCodeCamp Exercise Tracker Project on Replit.
my Project Link: https://replit.com/@mazorSharp/Exercise-Tracker?v=1
If you click on the link, the code I’m referring to is in the server.js file and It’s the code under the comment labeled // NUMBER 3

I’m running into an issue with one of the GET routes.
GET user’s exercise log: GET /api/users/:_id/logs?[from][&to][&limit]

The GET route works fine when all queries are used in the get search. Queries for the test are From, To, and Limit. If one of the queries aren’t present in the GET request I get an error.

CastError: Cast to date failed for value “Invalid Date” (type Date) at path “date” for model “exerciseInfo”

What steps would I need to take to make sure if someone isn’t putting in values for FROM, TO, and LIMIT queries that it wouldn’t throw an error because of it?

app.get('/api/users/:_id/logs', (req, res) => {

  const {from, to, limit} = req.query;
  let idJson = {"id": req.params._id}
  let idToCheck = idJson.id;

  console.log("from=> ", from, "to=> ", to, "limit=> ", limit, "idToCheck=> ", idToCheck);

  //Check ID
  ExerciseInfo.findById(idToCheck, (err, data) => {
if (err) {
  console.log("Error with ID => ", err);  
} else {

  // Find Username Documents
  ExerciseInfo.find(({username: data.username}, {date: {$gte: new Date(from), $lte: new Date(to)}}), null , {limit: +limit} , (err, doc) => {
    let loggedArray = []
    if (err) {
      console.log("error with username=> ", err);
    } else {

      console.log("all docs related to username=> ", doc);
      let documents = doc;
      let loggedArray = documents.map((item) => {
        return {
          "description": item.description,
          "duration": item.duration,
          "date": item.date.toDateString(),
        }
      })
      
      const test = new LogInfo({
        // "_id": idToCheck,
        "username": data.username,
        "from": from,
        "to": to,
        "count": limit,
        "log": loggedArray,
      })

      test.save((err, data) => {
        if (err) {
          console.log(err);
        } else {
          console.log("saved exercise successfully")
          res.json({
            "_id": idToCheck,                
            "username": data.username,                
            "from": data.from.toDateString(),
            "to": data.to.toDateString(),
            "count": data.count,
            "log": loggedArray,
          })
        }
      })  
    }
  })
}

})
})