React Function filter does not work (no errors in the console)

In my list, when I click on row, the background of the changes color and the id of my row is added to the array of my state. It works, but when I do the reverse my array doesn’t get empty when I use the filter function (line 15).

import React, {useState} from 'react';
import './Liste.css';
import Button from '../Button/Button';

function Liste(props) {

    const [nbLine, setNbLine] = useState([]);

    const clickLine = (e) =>
    {
        if (e.target.parentNode.className.length > 0)
        {
            console.log(e.target.parentNode.id);
            e.target.parentNode.classList.remove("lineClicked");
            nbLine.filter(line => line != e.target.parentNode.id);
            console.log(nbLine);         
        }
        else
        {
            e.target.parentNode.classList.add("lineClicked");
            nbLine.push(e.target.parentNode.id);
            console.log(nbLine);
        } 
    }

    const doubleClickLine = () =>
    {
        console.log("doubleClickLine"); 
    }

    return (
        <>
            <table className='tableList'>
                <thead>
                    <tr>
                        {props.headers.map((header, h) =>
                            <th key={h}>{header}</th>                   
                        )}
                    </tr>
                </thead>
                <tbody>
                    {props.records.map((record, r) =>
                        <tr key={r} id={props.table+"_"+record[0]} onClick={clickLine} onDoubleClick={doubleClickLine}>
                            {props.columns.map((column, c) =>
                                <td key={c}>{record[column]}</td>      
                            )} 
                        </tr>                
                    )}
                </tbody>
                <tfoot>
                    <tr>
                        <th colSpan={7}>
                            {props.buttons.map((button, b) =>
                                <Button key={b} id={button[0]} type={button[1]} value={button[2]} click={button[3]}/>              
                            )}
                        </th>
                    </tr>
                </tfoot>
            </table>
        </>
    )
}

export default Liste;

Here is the screen when I click (the elements are in the table).
Note: the data is fictitious.

And here is the screen when I click again (the elements resent in the array).

And here is the screen when I click again (the elements resent in the array).

Why is the filter function not working?

How to filter array of dates using javascript

I’ve got an array of dates (strings) in sorted order, going from oldest to latest days, like so:

const allDates = [
  '2020-11-21',
  '2020-11-22',
  '2020-11-23',
  '2020-12-21',
  '2020-12-22',
  '2020-12-23',
  '2021-01-21',
  '2021-01-22',
  '2021-01-23',
  '2021-02-21',
  '2021-02-22',
  '2021-02-23'
];

What I want to create is a new array with the oldest date from the oldest month, any dates from the middle months (could be the first date of each month) and the last date of the latest month, so the new array looks like this:

const filteredDates = ['2020-11-21', '2020-12-21', '2021-01-21', '2021-02-23']

The important thing is that I don’t want to use any JS library

Moving on from ExpressJS [closed]

So I am currently using Express as my defacto library for backend. But, I want to change. I have come across a lot of options like Fastify, Adonis, Koa & more. But, Express is a low-scope framework & I like its approach. But, while choosing a new framework, I am not sure if I should go for a full-fledged system like Adoni.

Function works but won’t return HTML?

I have a component that returns the following code:

  <Popup
    toggled={moveFolderPopup}
    width="50%"
    close={() => setMoveFolderPopup(false)}
  >
    <div className="popup-title">
      {t('view.assets.moveFolderPopup.title')}
    </div>
    <div className="filebrowser-moveFolderPopup-hierarchy">
      {renderFolderStructure(indexFolder.id)}
    </div>
  </Popup>

The part that’s failing is renderFolderStructure(indexFolder.id)
The function looks as follows:

const renderFolderStructure = (parentId: string) => {
if (assetFolders !== []) {
  assetFolders.map((folder, i) => {
    if(folder.parentId === parentId) {
      console.log('why wont this work?');
      return <div>{folder.name}</div>;
    }
  });
} else {
  return <div>Error</div>;
}
};

Running this code the console prints out “Why wont this work?” 6 times for 6 folders that have matching parentIds. So everything works except that the function won’t return <div>{folder.name}</div>. I feel like I have done something like this a million times. What’s wrong here?

How to send information between two html using json and POST?

In ‘cart.html’ I have a form of id=”order-selection-cart” which is for selecting user’s order, which the user wants to make payment for.

<select id="order-selection-cart" onchange="order_cart()" class="form-control">
          {% for order in orders_for_user %}
              <option>{{order.id_zamowienie}}</option>
          {% endfor %}
</select>

In the same html page, I also display the selected order value ({{order.id_zamowienie}} in a form of id=”order-selection-cart”:

<div class="row cart-box" style="background-color:rgb(226, 226, 226);">
            <h10>Szczegóły zamówienia </h10>
            <h4 type="value" id="order-details"></h4>
</div>

Now, I want to go to ‘checkout.html’ by clicking a button of name ‘Zamawiam’ and I have done it like this:

<div class="row cart-box" style="background-color:rgb(226, 226, 226);">
            <h4>Suma zamówienia</h4>
            <h10>Suma: {{cart_total|floatformat:2}} zł</h10>
            <br>
            <a class="btn btn-primary" href="{% url 'checkout' %}" role="button">Zamawiam</a>
</div>

This code works, but I have a problem with remembering selected user’s order which he wants to make payment for. Let’s say I selected option 2, I want to remember it and when clicked ‘Zamawiam’ I want to go to ‘checkout.html’ where this value (2) can be accessed and not changed when it is again changed (if user changes it in cart.html in other window for example). At first I have had js code which was changing value of selected option in ‘cart.html’:

// ordernumber update in cart.html
function order_cart() {
    let user = '{{request.user}}'
    let select = document.getElementById('order-selection-cart');
    let select1 = document.getElementById('order-details');

    let value = select.options[select.selectedIndex].value;
    select1.innerHTML = value;
}

Then I thought of adding a POST method, but it would be run every time user changes his order in cart.html. I want to run a POST method each time a user clicks ‘Zamawiam’ with content of current order option which was selected by user. I also would like to ask how to then access ‘order_number’ in a checkout.html code.

// ordernumber update in cart.html
function order_cart() {
    let user = '{{request.user}}'
    let select = document.getElementById('order-selection-cart');
    let select1 = document.getElementById('order-details');

    let value = select.options[select.selectedIndex].value;
    select1.innerHTML = value;

    // send information about selected option to 
    alert('USER:', user)
    if(user === 'AnonymousUser'){
        console.log('Not logged in')

        // TODO: delete it once login is done 
        update_order_number(value);
    }else{
        update_order_number(value);
    }

}

function update_order_number(order_number){
    console.log('User is logged in, sending data...')

    let url = '/checkout/'

    // whenever we are sending POST data to the backend in Django, is we need to send CSRF token
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'order_number': product_id// body data type must match "Content-Type" header
        })
    })


    .then((response) => {
                return response.json()
            })

            .then((data) => {
                console.log('data: ', data)
            })
} 

Vue JS lodash findKey nested object with dot notation returns undefined

I’m trying to pull out a value for a nested object key from some eligibility array that I’ve got, but I’m getting an undefined value for some reason and need to know what I’m missing.

Given the following array:

const eligibilityCriteria = [
  { field: 'loan.amount', operator: '>=', value: 1000 },
  { field: 'loan.term', operator: '>=', value: 1 },
  { field: 'applicant.birthday', operator: '>=', value: 40 },
  { field: 'applicant.isHomeowner', operator: '==', value: false }
]

I need to find loan.amount from a nested object and pull out it’s value:

My big nested object is (coming from the store)

application: {
  meta: {
    brand: '',
    version: '',
    affiliate: '',
    affiliate_full: '',
    campaign: '',
    client_hostname: '',
    client_href: '',
    client_origin: '',
    client_useragent: '',
    client_ip: '127.0.0.1',
    icicle_hash: ''
  },
  loan: {
    amount: 500,
    term: null,
    purpose: null
  }
}

My function right now is:

checkEligibility () {
  const eligibilityCriteria = [
    { field: 'loan.amount', operator: '>=', value: 1000 },
    { field: 'loan.term', operator: '>=', value: 1 },
    { field: 'applicant.birthday', operator: '>=', value: 40 },
    { field: 'applicant.isHomeowner', operator: '==', value: false }
  ]

  for (const [index, offer] of this.datasets.offers.entries()) {
    const eligibility = eligibilityCriteria

    if (eligibility) {
      for (const [ci, criteria] of eligibility.entries()) {

        // TODO: this fails to pull the value, returns undefined
        const field = _.findKey(this.$store.state.application.application, criteria.field)
      }
    }
  }
}

What am I missing?

Use variable in ejs script tag

I want to use variable (or variables) in ejs file in the script tag ,I also want to pass the rendered file to a function for taking screenshot from ejs file.

But now I have 2 problems :

1.I don’t know how to pass the variable in server file to the ejs file and render and use it without app.get… (in express) because it’s server side and I want to use html file.

2.I don’t know how to use variable in ejs file in the script tag

these are my files :

index.ejs


<div id="tvchart"><% symbol %></div>

<script>
//some codes 
 var symbolD =<%= symbol %>;
fetch(`http://127.0.0.1:9665/fetchAPI?endpoint=https://api.binance.com/api/v3/klines?symbol=${symbolD}&interval=1m&limit=1000`)
</script>

server.js

// set the view engine to ejs
app.set("view engine", "ejs");
const symbol = "EGLDUSDT"

const file = ejs.render("./index.ejs" , symbol);
console.log(file)

So Why my ejs and server file doesn’t work?

Passing numeric data containing django to javascript

am having a problem with char inside numeric data, it’s too large to be cleaned. anyways.
I want to replace < and > from value.
just posting relevant codes.
views.py

def search_result(request):
    if request.method == "POST":
        ChemSearched = request.POST.get('ChemSearched')
        tarname = BINDLL.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched).exclude(ki_nm__isnull=True)[:120]
        
        return render(request, 'Search/search_result.html',{'ChemSearched':ChemSearched,'tarname':tarname})

Html side

<script>
     data=[{% for Bindll in tarname %} {
                group: '{{ Bindll.targetnameassignedbycuratorordatasource }}',
                     variable:'{{ Bindll.zincidofligand}}',
                     value: {{Bindll.ki_nm|safe}}
                    }, {% endfor %}];

which is used by graph d3.js.
all go well unless I have ‘<‘ or ‘>’ in value I’ll have this result

Uncaught SyntaxError: Unexpected token ‘>’
or if use escape value: {{Bindll.ki_nm|escape}}
Uncaught SyntaxError: Unexpected token ‘&lt’
any function to be used in Html side javascript to replace char or anything and keep only numeric like regex replace.
thanks.

firebase initialize with vuejs 2022

i wish to initialize my vuejs project with firebase.

But because of the new update i can’t.

i must use import { initializeApp } from "firebase/app"; AND const app = initializeApp(firebaseConfig);

but i have 2 problems with this:

1)

This dependency was not found: To install it, you can run: npm install –save firebase

it didn’t found my module. In my package.json it’s present.

2)

to initialize my instance vuejs i need to write :

new Vue({ router,render: h => h(App)}).$mount('#app')

but i have “app” from firebase missing.

thanks for your help 🙂

react native local push notifications IOS – (react-native-push-notification)

I’m using the (react-native-push-notification) package for my alarm ios app but there is an issue when the app is in the background notification banner appears for a short time but does not receive any callback in the background because I need a callback, where I ring a sound continuously.
When the app is in the background notification banner appears with sound only for 6 seconds but I need to play a sound continuously when a notification appears in the background.

How do I understand my addEventListener error code? [duplicate]

I’m attempting to build a simple ‘To-Do List’. I’m trying to add a new P element to my existing div. Does anyone have any ideas regarding the following error code?

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

I feel like my HTML button (submitButton) click isn’t being received, although I could be wrong.

var toDoList = document.getElementById("toDoList"); // div with p elements within
var submitButton = document.getElementById("submitButton"); // HTML button
var textInput = document.getElementById("textInput"); // HTML text input

function addFunction(){
    var newItem = toDoList.createElement("p");
    newItem.innerText = textInput.value;
    document.toDoList.appendChild(newItem);
}

submitButton.addEventListener('click', addFunction);

Show an element only if the data given by the Api exists

I’m using Pokeapi and want to display the types of the pokemon in 2 different element bc I’m applying a style (the background color) according to the type of the pokemon. The problem is that it shows the first 3 pokemon but not the fouth bc it has only one type and it can’t find the second type (which doesn’t exist) in the data given by the api.

Here’s my JS :

function displayPokemon (pokemon) {
    const pokemonEl = document.createElement('li');
    const name = pokemon.name;
    const type1 = pokemon.types[0].type.name;
    const type2 = pokemon.types[1].type.name;
    const pokemonHTMLString =
        `
        <div class="pokemon_container ${type1} ${type2}">
            <div class="pokemon_container_image">
                <img class="pokemon_container_image_sprite" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png" loading="lazy" alt="${name}"/>
                <img class="pokemon_container_image_shiny" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/${pokemon.id}.png" loading="lazy" alt="${name}"/>
            </div>
            <h3 class="pokemon_number">#${pokemon.id.toString().padStart(3, '0')}</h3>
            <h2 class="pokemon_name" onClick = "selectPokemon(${pokemon.id})">${name}</h2>
            <a class="pokemon_type" id="${type1}">
                <img id="${type1}" alt="${type1}"></img>
                <span>${type1}</span>
            </a>
            <a class="pokemon_type" id="${type2}">
                <img id="${type2}" alt="${type2}"></img>
                <span>${type2}</span>
            </a>
        </div>
    `
    pokemonEl.innerHTML = pokemonHTMLString;
    pokedex.appendChild(pokemonEl);
};

Here’s the error : “Uncaught (in promise) TypeError: pokemon.types[1] is undefined”

Before that I was mapping the types and showing them in one element but I want to do 2 separate elements and I don’t know if my code is wrong and I have to modify something or if I have to create a function or an if else statement.

Redux State changes but component not rerendering

My issue is that my redux state is updating (I can see it in the redux dev tool) but my component is not updating, it’s not putting the last value of my array initialState.userWeight
Here is what my reducer looks like :

case 'NEWWEIGHT':
           const weight = action.payload.weight
           const date = action.payload.date
           state.userWeight = [...state.userWeight, {weight: weight, date: date}]
           return {...state}

Here is my initialState :

const initialState = {
    userName: '',
    userSize: 0,
    userWeight: [],
    userDate: '',
}

Here is what my component looks like :

    const userWeightRedux = useSelector(state => state.userInfo.userWeight[Array.length - 1].weight)

    console.log(userWeightRedux)

...
<Text style={styles.user}>{userWeightRedux}</Text>

So console.log(userWeightRedux) dosen’t change.
I am new to react, redux and don’t fully understand the spread syntax, maybe the problem is here but did’nt find anything, hope you can help me :).

Can I use regex within toHaveClass?

I have an element with a long class that contains a dynamic suffix to denote the type of icon that should be displayed, think of some-very-long-classname-for-an-icon-{iconType}, where {iconType} is likely to be filled with a string like success or error etc.

In React Testing Library, I am wanting to assert that I have a particular icon class applied, however I don’t want to clutter up my tests by having the full prefix some-very-long-classname-for-an- at each part.

Rather than store this prefix as a variable I was wondering if it would be possible to use regex to specify? Something along the lines of /icon-success$/.

I was thinking of using toHaveClass as I know this will work when specifying the full class name for the test:

expect(myComp).toHaveClass('some-very-long-classname-for-an-icon-success');

however, upon my travels I have found that toHaveClass doesn’t take Regex 🙁

I did think of doing something along the lines of

expect(myComp).toHaveClass(expect.stringContaining('icon-success'));
expect(myComp).toHaveClass(expect.stringMatching(/icon-success$/));

however these also didn’t seem to work…