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,
          })
        }
      })  
    }
  })
}

})
})

I am attempting to get my react application deployed via github pages

It works perfectly fine when I boot it up on LOCALHOST(npm start) but when it’s deployed, it doesn’t display my pages and components calls inside my App.js I am using react-router-dom (version 6.0.2).

APP.JS:

import React from "react";
import Navbar from "./components/Navbar/Navbar";
import Footer from "./components/Footer/Footer";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import Home from "./pages/Home";
import Search from "./pages/Search";
import Compare from "./pages/Compare";

function App() {
  return (
  <>
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/search" element={<Search />} />
        <Route path="/compare" element={<Compare />} />
      </Routes>
      <Footer/>
    </BrowserRouter>
  </>
  );
}

export default App;


Link to repo: https://github.com/ntommy06/CS410P-FinalProject

Looping through Buttons to get their Src attribute if selected

I’m using vanilla javascript and currently trying to loop through each button. If the button if clicked, change some .style attributes and push the image.src into an array. I’m having trouble creating code that can selected multiple .src’s but not ALL of the srcs. Even if they aren’t clicked all the .src’s still show up on my console. I just am at a total blank.

for (let i = 0; i < favoriteBtn.length; i++) {
  let btn = favoriteBtn[i];
  let favoriteTheme = false;
  let imgCard = document.getElementsByClassName("card");

  btn.addEventListener("click", () => {
    for (let i = 0; i < Array.from(imgCard).length; i++) {
      let card = imgCard[i].src;

      if (favoriteTheme == false) {
        btn.style.backgroundColor = "red";
        btn.style.color = "white";
        favoriteTheme = true;
        // images.push(`'${card}'`);
      } else {
        btn.style.backgroundColor = "";
        btn.style.color = "";
        favoriteTheme = false;
      }
    }
  });
}

firestore not returning any indication that a new document add was succesful or not

I think this is not right, or i am the one not doing it well, so when i add a new document to the firestore collection, i can use the ref to get the id, but when i pass a wrong collection name, I still get the same response, why isn’t firestore throwing an error.

async function addDoc(collection, data) {
    try {
        const db = admin.firestore();
        const ref = await db.collection(collection).doc() //add(data);
        ref.set(data);
        console.log("Document successfully added!", ref);
    }
    catch (err) {
        console.log("Error adding document: ", err);
    }
}

i want to know why this is behaving like this, and how to detect if the new document was created. Thanks

How to setup Firebase Cloud Messaging v9 in React?

I’m having trouble setting up my firebase environment in React.
I’m going through the firebase documentation, but I can’t seem to get the first step of getting permission correct.

I tried looking everywhere to fix these errors, but all attempts failed. Please help!

Errors:

Service worker registration failed, error: TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token.  FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8080/firebase-cloud-messaging-push-scope') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).

Code:

src/index.js

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../firebase-messaging-sw.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function(err) {
    console.log('Service worker registration failed, error:', err);
  });
}
src/firebase.js

import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

const firebaseApp = initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
});

const messaging = getMessaging(firebaseApp);
    
export const fetchToken = async (setToken) => {
  await getToken(messaging, { vapidKey: KEY_PAIR }).then((currentToken) => {
    if (currentToken) {
      setToken(currentToken)
    } else {
      console.log('No registration token available. Request permission to generate one.');
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
  });
}
public/firebase-messaging-sw.js

import { initializeApp } from "firebase/app";
import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw";

const firebaseApp = initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
});

const messaging = getMessaging(firebaseApp);

onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: ''
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

Getting Promise Pending in selenium for a web element used in an assertion

I am just trying to run a simple test using selenium with chai library for assertion. Webdriver executes a script to set a token for login. I can see on the UI that it login fine but the test fails on the assertion with web element status being promise pending. Any idea what am i missing here. thanks!

Here is the piece of code

const {Builder, By, Key, until} = require('selenium-webdriver');
let chai = require('chai');
let expect = chai.expect;
require('chromedriver');

(async function example() {
    let driver = await new Builder().forBrowser('chrome').build();
        await driver.get('http://localhost:4200/login');
        driver.executeScript('window.localStorage.setItem("token", "xyz");');
        driver.executeScript('window.localStorage.setItem("lastAction", "' + Date.now() + '");');
        await driver.wait(until.titleIs('XXXX'), 1000);
        expect(driver.findElement(By.id('welcome-header')).getText()).to.equal('ZZZZZ');

})();

And below is the error what i get

expect(driver.findElement(By.id('welcome-header')).getText()).to.equal('ZZZZZ');
                                                                         ^
AssertionError: expected {} to equal 'ZZZZZ'
    at example (******e2e-spike-copytestslogin_test_copy.js:13:74)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  showDiff: true,
  actual: Promise { <pending> },
  expected: 'ZZZZZ',
  operator: 'strictEqual'
}

Select Dropdown, make default Value not a selectable option

I have a form I want users to fill out. I have an array of options they can choose from but I don’t want any of them to be the default. I would like the drop down to say something like –Select– . Then when the users selects the dropdown, they can no longer select –Select–.

I am using Redux forms and React-Bootstrap for the presentation. I seen some answers on Stack Overflow, they say set the option to disable or add it as an option group. This resolve how it behaves when the dropdown opens but removes that option as a default option.

  let selectOptions = options.map((option, index) => {
    return (
      <option key={index} value={option}>
        {option}
      </option>
    );
  })
  const {value, ...inputs} = input
  
    return (
    <Aux>
      <Form.Label className="mb-1">{label}</Form.Label>
      {explanation && !readonly ? (
        <OverlayTrigger
          trigger="click"
          key={"right"}
          placement={"right"}
          overlay={
            <Popover id="popover-basic">
              <Popover.Header as="h3">{label}</Popover.Header>
              <Popover.Body>{explanation}</Popover.Body>
            </Popover>
          }
        >
          <i className="material-icons text-info align-top ml-2 cursor">help</i>
        </OverlayTrigger>
      ) : null}
      <Form.Control
        className={`${formStyle} ${validationStyle} ${noValidationStyle}`}
        disabled={readonly}
        as="select"
        placeholder="select"
        {...input}
        isInvalid={(touched || attempt) && !!error}
        isValid={!error}
      >
        {selectOptions}
      </Form.Control>

      {(touched || attempt) && !!error && !readonly ? (
        <Form.Control.Feedback type="invalid" className="animated fadeIn">
          {error}
        </Form.Control.Feedback>
      ) : (
        <span>{"u00A0"}</span>
      )}
    </Aux>

How to load ajax to the table (authorization is success now in console log on html)

after a few error and trials i have managed to authorize my data and load into the html but however now how can i call the api from database and load into my table

here the code for my file

<table id="infoTable" class="table" style="width: 920px; margin: 0; padding: 0; border: 0;">
                                <thead>
                                  <tr>
                                    <th scope="col" style="text-align: justify;"> </th>
                                    <th scope="col" style="text-align: center; padding-right: 2px;"></th>
                                    <th scope="col" style="text-align: center;"></th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <tr>
                                    <td scope="row" style="padding-left: 45px;"></td>
                                    <td style="text-align: center;"></td>
                                    <td style="text-align: center;"></td>
                                  </tr>
                                
                                </tbody>
                                
                              </table>  

here the ajax file

$.ajax({
                                // The url that you're going to post
                                /*

                                This is the url that you're going to put to call the
                                backend api,
                                in this case, it's
                                https://ecoexchange.dscloud.me:8080/api/get (production env)

                                */
                                url:"https://ecoexchange.dscloud.me:8080/api/get",
                                // The HTTP method that you're planning to use
                                // i.e. GET, POST, PUT, DELETE
                                // In this case it's a get method, so we'll use GET
                                method:"GET",
                                // In this case, we are going to use headers as
                                headers:{
                                    // The query you're planning to call
                                    // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
                                    query:"RecyclableGet(0)",
                                    
                                    // Gets the apikey from the sessionStorage
                                    apikey:sessionStorage.getItem("apikey")
                                },
                    
                                success:function(data,textStatus,xhr) {
                                    

                                        console.log(data);
                                },
                                error:function(xhr,textStatus,err) {
                                    console.log(err);
                                }
                            });

So this is all i have currently i trying to load my database into the table but so far i am receiving is a blank empty table, needed some help and advise here
Thanks