TinyMC text area isn’t encodes correctly to the MongoDB

While saving data to MongoDB, the characters that generated from a text area isn’t generates correctly within the database, the output is just none (”), I’ve tried to change the input’s unicode but nothing appeared to work. I will appreciate your help to let me know what I did wrong – and of course I will learn from it 😉

My whole JS’ code

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var http = require('http').Server(app)
var io = require('socket.io')(http)
var mongoose = require('mongoose')

app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

mongoose.Promise = Promise

var dbUrl = 'mongodb+srv://username:[email protected]/database'


var Message = mongoose.model('Message', {
    name: String,
    message: String
})

app.get('/messages', (req, res) => {
    Message.find({}, (err, messages) => {
        res.send(messages)
    })
})

app.get('/messages/:user', (req, res) => {
    var user = req.params.user
    Message.find({name: user}, (err, messages) => {
        res.send(messages)
    })
})

app.post('/messages', async (req, res) => {

    try {
        var message = new Message(req.body)

        var savedMessage = await message.save()

        console.log('saved')

        var censored = await Message.findOne({ message: 'badword' })

        if (censored)
            await Message.remove({ _id: censored.id })
        else
            io.emit('message', req.body)

        res.sendStatus(200)
    } catch (error) {
        res.sendStatus(500)
        return console.error(error)
    } finally {
        console.log('message post called')
    }
})


mongoose.connect(dbUrl, { useMongoClient: true }, (err) => {
    console.log('MongoDB status is', err)
})

Show/Hide Div using RegEx and Javascript based on input inside table/array

First let me say that i’m pretty new to html/javascript. I dont even know if I asked my question the right way.

I currently have the following table:

<table id="ItemTable" class="table">
        <thead>
            <tr>
                <th>Item Description</th>
                <th>Item Number</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr id="tablerow0">
                <td>
                    <input type="text" class="form-control" id="ItemDesc[0]" required>
                </td>
                <td>
                    <input type="text" class="form-control" id="ItemNum[0]" required>
                </td>
                <td>
                    <button type="button" class="btn-sm btn-secondary" onclick="removeTr(0);">Delete</button>
                </td>
            </tr>
    </table>
    <p>
        <button id="add" type="button" class="btn-sm btn-secondary">Add Item</button>
    </p>
    <hr />
    </tbody>
    </table>

The script behind it:

var counter = 1;
    $(function () {
        $('#add').click(function () {
            $('<tr id="tablerow' + counter + '"><td>' +
                '<input type="text" class="form-control" id="ItemDesc[' + counter + ']" value="" required="required" />' +
                '</td>' +
                '<td>' +
                '<input type="text" class="form-control" id="ItemNum[' + counter + ']" value="" required="required" />' +
                '</td>' +
                '<td>' +
                '<button type="button" class="btn-sm btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                '</td>' +
                '</tr>').appendTo('#ItemTable');
            counter++;
            return false;
        });
    });
    function removeTr(index) {
        if (counter > 1) {
            $('#tablerow' + index).remove();
            counter--;
        }
        return false;
    }

What i’m trying to do is when user entered text in the ItemDesc field matches a certain RegEx than a div will appear. If I use just a standard text box for test, my function is working fine. How do I use the ItemDesc from inside the table as well as from any new rows added?

$('#ItemDesc[0]').keyup(function() {
            var regex = new RegExp(/(one)|(two)|(three)/gi);
            var  VAL = this.value;
            if(!regex.test(VAL)){
                $('#TestDiv').hide();
            } 
            else
            {
              $('#TestDiv').show();                 
            } 
        });

How do I display every element from my localStorage item?

i’m trying to create a simple To-do list, and my question is how do i get all elements of a single item in localStorage displayed?

pushing things into localStorage in a form of an array works fine, but only thing I see on my page is the first index of the “tasks” array.

const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasks = []

function createTask(){
    if(inputEl.value.length != 0){
        

    const newDiv = document.createElement("div")
    newDiv.classList.add("task")
    const newParagraph = document.createElement("p")
    const newCancelBtn = document.createElement("button")
    newCancelBtn.classList.add("cancelBtn")
    newCancelBtn.textContent = "X"
    const newDoneBtn = document.createElement("button")
    newDoneBtn.classList.add("doneBtn")
    newDoneBtn.textContent = "Done"

    todoListContainer.appendChild(newDiv)
    newDiv.appendChild(newParagraph)
    newDiv.appendChild(newCancelBtn)
    newDiv.appendChild(newDoneBtn)
    //^^ Creating a container for a new task, with all its elements and assigning the classes^^
    
    tasks.push(inputEl.value)
    localStorage.setItem("tasks", JSON.stringify(tasks))
    inputEl.value = ""

    newParagraph.textContent = JSON.parse(localStorageContent)

    errorMsg.textContent = ""

    }else{
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")
        
    }

}

submitBtn.addEventListener("click", () =>{
    createTask()
    
    
})

What is the standard or best practice with regards to quotes on JavaScript keys?

I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven’t found anything and would like to know (before building a huge project on bad practices) which is best between:

obj = {'foo': 'bar'}

and

obj = {foo: 'bar'}

Or better yet, is there some document I can refer to for this?

How do I remove an apple mapkit-js Annotation Callout?

I have not been able to find any documentation on how to close an Annotation call out when clicking on a pin(Annotation) on the map. When I click on an Annotation my custom callout appears. In that callout I added a close button. I know you can click on the map to hide the annotation but I also require a close button in this case.

I created a hacky way to close the popup however, I would like to know if there is a better method?

jQuery('.landmark').fadeOut();

I see there is a deselectAnnotation(_:animated:) option however that is only available for the MapKit and not Mapkit-js it appears, unless I’m overlooking something.

How to verify email in firebase auth?

I am using expo client for my app. When I send the email, the verification immediately fails. When I go to the email and verify it, the verification still doesn’t work. This is my function:

firebase.auth().createUserWithEmailAndPassword(emailID, password)
                .then(async ({user}) =>{
                    //console.log(this.state)
                    await user.sendEmailVerification().then(async() => {
                        user = await firebase.auth().currentUser;

                        await user.reload();

                        user = await firebase.auth().currentUser;
                        if(user.emailVerified) {
                            db.collection("Users").add({
                                'firstName': this.state.firstName,
                                'lastName': this.state.lastName,
                                'contact': this.state.contact,
                                'emailID': this.state.emailID,
                                'password': this.state.password,
                                'description': '',
                                'profilePicture': ''
                            })
                            return alert('Account has been created. You can now login.');
                        } else {
                            return alert('Failed to verify email!')
                        }
                    })
                })
                .catch((error) => {
                  // Handle Errors here.
                  var errorCode = error.code;
                  var errorMessage = error.message;
                  return alert(errorMessage);
                });

Can anyone please provide me a solution for this? Thanks,

Recursive map function for nested array

I’m trying to create a map function that supports computing nested arrays, using recursion:

This function, when a unidimesional (eg. [1,2,3,4] ) array is used works fine:

const map = (oldArray, callback, newArray = []) => {

    //base case: check if there are any items left in the original array to process
    if (oldArray.length <= 0){
      //if all items have been processed return the new array
      return newArray
    } else {
      //destructure the first item from old array and put remaining in a separate array
      const [item, ...theRest] = oldArray
      // create an array of the current new array and the result of the current item and the callback function
      const interimArray = [...newArray, callback(item)]
      // return a recursive call to to map to process the next item.
      return map(theRest, callback, interimArray)
    }

  }

But, I want to support a nested array, so for example, I have an array like this:

const array = [1,[1,2],3]

and I want to apply a function, eg: (x)=>x+1;

I have this implementation so far, but I can’t wrap my mind around it.

function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    const interimArray = [...newArr, fn(item)];

    return rnMap(rest, fn, interimArray);
  }
}

const rnRes = rnMap(nArr, (e) => {
  return e + 1;
});

console.log(rnRes);

It returns [ 2, [ 2, 2 ], 2, 2 ] but it suppose to return [2,[2,3],4]

If anyone could help me will be appretiated.
Thanks in advance.

Multiple middlewares in express

How can I use multiple middleware in express I tried this:

AuthRouter.post("/login", [ValidInfo, limiter], async (req, res) => {

And I get this error:

ReferenceError: Cannot access 'limiter' before initialization
    at file:///C:/Users/lokop/Projects/idk/server/Routes/Auth.js:64:39
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

disabled button after submit form with model validation asp.net core

How Can I disable button after submit form with model validation in asp.net core?

code:

                    <form action="/AddComment" method="post" id="InsertCommentForm">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <div class="form-group">
                            <input type="hidden" asp-for="ProductId" />
                            <input type="hidden" asp-for="ParentId" value="" id="reply" />
                            <input asp-for="Email" id="Email" class="form-control mrg15B" placeholder="لطـفا یک ایمیل معتبر وارد کنید">
                            <span asp-validation-for="Email" class="text-danger"></span>

                            <input asp-for="FullName" id="FullName" class="form-control mrg15B" placeholder="لطـفا نام خود را وارد کنید">
                            <span asp-validation-for="FullName" class="text-danger"></span>

                            <textarea asp-for="Text" id="Text" class="form-control mrg15B area" cols="60" rows="5" placeholder="لطفا متن پیام را وارد کنید"></textarea>
                            <span asp-validation-for="Text" class="text-danger"></span>

                            <br />
                            <input type="submit" value="ارسال" id="InsertCommentBtn" class="btn btn-warning">
                        </div>
                    </form>

I tested several times, but if the validation model starts working and prevents the form from being posted, the Disable button remains.

Thankyou

Mix useEffect and Firebase’s onValue

When working with Firebase and React, in order to fetch data based on state changes or on inner database changes (from another user for example), I often rely on pieces of code like this one:

    useEffect(() => {

    const getGamesInSelectedGroup = () => {

        if (!state.currentGroup) {
            return
        }

        const db = getDatabase();
        const resp = ref(db, `/games/${state.currentGroup.name}`);

        onValue(resp, (snap) => {
            if (snap.exists()) {
                const data = snap.val()
                const games = Object.keys(data).map(k => ({id: k, group: state.currentGroup.name, ...data[k]}))

                setState((prev) => ({
                    ...prev,
                    games: games,
                    isLoaded: true,
                }));
                return

            }
            setState((prev) => ({
                ...prev,
                games: null,
                isLoaded: true,
            }));
            toast.warning("no data for " + state.currentGroup.name)

        })
    }

    getGamesInSelectedGroup();

}, [state.currentGroup])

However, I am wondering if, whenever state.currentGroup changes, a new listener to /games/${state.currentGroup.name} is created? If so, is there a mean to unsubscribe to previous listener before creating a new one?

I have thinking about replacing onValue by a get call, still conditioned on state.currentGroup and using onValue outside useEffectto reflect “inner” database change.

Change div content on mouse hover with default content fallback

I’ve implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don’t really want to go with another solution if it can be avoided. I’m trying to figure out one more piece of the puzzle though…

I can’t seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

<div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')">Apple</li>
    <li onmouseover="hover('oranges are healthy')">Orange</li>
    <li onmouseover="hover('Candy is the best')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>