How can I write a function to scroll to an element with useRef?

Having trouble scrolling into view when passing props to my function.

–This works:

const scrollTo = useRef(); 
const executeScroll = () => scrollToMe.current.scrollIntoView();

And the div:

<div ref={scrollToMe}>Scroll to me</div>

And the button:

<button onClick={executeScroll}> Click to scroll </button>

—
But this doesn’t work:

const scrollTo = useRef(); 
const executeScroll = (scrollTo) => scrollTo.current.scrollIntoView();

And the div:

<div ref={scrollToMe}>Scroll to me</div>

And the button:

<button onClick={executeScroll(scrollToMe)}> Click to scroll </button>

I have tried writing it like this:

const executeScroll = (scrollTo) => [scrollTo].current.scrollIntoView();

CSS property changing then going back to initial value instantly

I want to change the CSS properties permanently, in this example i want to hide the text ‘Hide me’ and show ‘Show me’ instead after clicking on the ‘Next’ button.

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="test.css">
    <script type="text/javascript" src="test.js"></script>
</head>
<body>
    <form>
        <input type="text" name="text">
        <input type="submit" value="Next" onclick="Next()">
    </form>
    <div id="hideme">Hide Me</div>
    <div id="showme">Show Me</div>
</body>
</html>

CSS:

#hideme
{
    display: block;
}
#showme
{
    display: none;
}

JavaScript:

function Next()
{
    document.querySelector('#hideme').style.display = 'none';
    document.querySelector('#showme').style.display = 'block';
}

React Native: bottom tab press not working

in my react-native app I have a bottom tabs navigation, I added a tabPress listener to one of the screens but for some reason now all screens don’t work, I can’t navigate to a different screen when I tap the icons…

The objective was to lock a screen depending of the day but now ALL screens are locked for some reason?

<Tab.Navigator /* options here... */>
        <Tab.Screen name="Descubre" component={STACK1} />
        <Tab.Screen name="Favoritos" component={STACK2} 
        listeners={{
          tabPress: (e) => {
              if(root.mapStore.isoWeekDay == 6)
              {
                e.preventDefault();
              }
          },
        }}
        />
        <Tab.Screen name="Pedidos" component={STACK3} />
        <Tab.Screen name="Más" component={STACK4}/>
    </Tab.Navigator>

recovering data from API [closed]

recovering data from api
Hello everyone,
I need some help about displaying data from an api

As you can see the first console.log allows to retrieve all data (name, price, address etc…) for 100 cryptos. While the second console.log allows you to retrieve only the price of the second crypto in the list
I would like to be able to display on my front-end the result of the second console.log, that is to say only one crypto at a time. For the moment my script allows me to display on the front end only the prices but of all the cryptos which does not suit me, I would like to be able to choose which one to display or not

Thanks in advance for your answers.

The script :

function App(){
const [data, setData] = useState([]);
const fetchData = () => {
  axios
  .get('http://localhost:4500/sushiswap')
  .then((res) => {
    console.log(res.data)
    console.log(res.data[1].price)
    setData(res.data)
  })
  .catch((err) => {
    console.log(err)
  })
}
useEffect(() => {
  fetchData()
}, [])

return(
  <Fragment>
    <ul>
      {data.map(item =>(
        <li key={item.name}>
          <p>{item.price.slice(0, 8)}</p>
        </li>
      ))}
    </ul>
  </Fragment>
)

Out for first console.log :
(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

0:
adress: “0x397ff1542f962076d0bfe58ea045ffa2d347aca0”
name: “USDC/ETHView chart”
price: “$1.0101$1.01010.000928 ETH0.000928 ETH”
[[Prototype]]: Object

There are 100 of these

out for second console.log :
$1,084.77$1,08545.38 ALCX45.38 ALCX

Javascript sounds and effects on buttons not working on click

Having trouble with javascript executing in html. To my knowledge the links and code is spelled correctly but I cant get the sound to play. No errors listed when I inspect the page and event listeners are listed but wont play sound. The last 4 are crossed out on purpose until i put in correct sounds. Here is my code…

var numberofAnimals = document.querySelectorAll(".animal").length;

for (var i = 0; i < numberofAnimals; i++) {

  document.querySelectorAll(".animal")[i].addEventListener("click", function() {

    var buttonInnerHTML = this.innerHTML;

    makeSound(buttonInnerHTML);

    buttonAnimation(buttonInnerHTML);

  });
}



document.addEventListener("keypress",function(event){

  makeSound(event.key);

  buttonAnimation(event.key);

});

function makeSound(key) {

  switch (key) {
    case "lion":
      var lion = new Audio("sounds/lion.mp3");
      lion.play();
      break;

    case "eagle":
      var eagle = new Audio("sounds/eagle.mp3");
      eagle.play();
      break;

    case "wolf":
      var wolf = new Audio("sounds/wolf.mp3");
      wolf.play();
      break;

    case "chicken":
      var chicken = new Audio("sounds/chicken.mp3");
      chicken.play();
      break;

    // case "cheetah":
    //   var cheetah = new Audio("sounds/cheetah.mp3");
    //   cheetah.play();
    //   break;
    //
    // case "mockingbird":
    //   var mockingbird = new Audio("sounds/mockingbird.mp3");
    //   mockingbird.play();
    //   break;
    //
    // case "giraffe":
    //   var giraffe = new Audio("sounds/giraffe.mp3");
    //   giraffe.play();
    //   break;
    //
    // case "elephant":
    //   var elephant = new Audio("sounds/elephant.mp3");
    //   elephant.play();
    //   break;

    default: console.log(key);
  }
}

function buttonAnimation(currentKey) {

  var activeButton = document.querySelector("." + currentKey);

  activeButton.classList.add("pressed");

  setTimeout(function() {
    activeButton.classList.remove("pressed");
  }, 100);

}
body {
  text-align: center;
  background-color: #FFF8E8;
}

h1 {
  font-family: 'Rubik Moonrocks', cursive;
  color: #202030;
}

.lion {
  background-image:url('../images/lion.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.eagle {
  background-image:url('../images/eagle.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.wolf {
  background-image:url('../images/wolf.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.chicken {
  background-image:url('../images/chicken.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.cheetah {
  background-image:url('../images/cheetah.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.mockingbird {
  background-image:url('../images/mockingbird.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.giraffe {
  background-image:url('../images/giraffe.png');
  background-size: contain;
  background-repeat: no-repeat;
}

.elephant {
  background-image:url('../images/elephant.png');
  background-size: contain;
  background-repeat: no-repeat;
}


.animal {
  outline: none;
  border: 1px solid #404B69;
  font-size: 1.5em;
  font-family: 'Arvo', cursive;
  line-height: 2;
  font-weight: 900;
  cursor: pointer;
  color: #DA0463;
  text-shadow: 3px 0 #DBEDF3;
  border-radius: 15px;
  box-shadow: 20px 20px 30px rgba(0, 0, 0, 0.2);
  display: inline-block;
  width: 150px;
  height: 150px;
  text-align: center;
  margin: 10px;
  background-color: white;
}

.animal:hover {
  box-shadow: 20px 20px 30px rgba(0, 0, 0, 0.5);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Click Safari</title>

    <link rel="stylesheet" href="css/style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <link href="https://fonts.googleapis.com/css2?family=Indie+Flower&family=Lobster&family=Rubik+Moonrocks&family=Smooch&display=swap" rel="stylesheet">

  </head>
  <body>
    <h1>Click Safari</h1>
    <h3>Click each animal to hear what they sound like</h3>
    <h3>Enjoy!</h3>

    <div class="set set1">
      <button class="animal lion">Lion</button>
      <button class="animal eagle">Eagle</button>
      <button class="animal wolf">Wolf</button>
      <button class="animal chicken">Chicken</button>
    </div>

    <div class="set set2">
      <button class="animal cheetah">Cheetah</button>
      <button class="animal mockingbird">Mockingbird</button>
      <button class="animal giraffe">Giraffe</button>
      <button class="animal elephant">Elephant</button>
    </div>



    <script type="text/javascript" src="script.js" charset="utf-8"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </body>
</html>

Double styles in devtools

I created an app in nuxt 3 (rc. 4). When you start the application, you will notice that the styles of the elements are duplicated. The problem only occurs when yarn dev is used (after generating an application with yarn generate problem disappears):

devtools image

As already mentioned, I use the nuxt version rc 4. In the previous version I didn’t notice this problem after.

package.json

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.1.1",
    "@fortawesome/pro-light-svg-icons": "^6.1.1",
    "@fortawesome/pro-regular-svg-icons": "^6.1.1",
    "@fortawesome/vue-fontawesome": "^3.0.1",
    "nuxt": "3.0.0-rc.4",
    "sass": "^1.52.2",
    "sass-loader": "^13.0.0"
  }
}

nuxt.config.ts

import { defineNuxtConfig } from 'nuxt'
import path from 'path';

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
    srcDir: path.join(__dirname, 'src'),
    alias: {
        '@': path.join(__dirname, 'src')
    },
    vite: {
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@import "@/assets/css/import.scss";'
                }
            }
        }
    },
    typescript: {
        shim: false,
        strict: true,
    },
    css: [
        '@/assets/css/global.scss',
        '@fortawesome/fontawesome-svg-core/styles.css',
    ],
    plugins: [
        '@/plugins/fontawesome.ts'
    ],
})

assets/global.scss

/*
    1. Fonts
    2. CSS reset
    3. Global styles
*/

// #############################################

// 1. Fonts
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,[email protected],300;8..144,400;8..144,500;8..144,600;8..144,700&display=swap');

// 2. CSS reset
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

// 3. Global styles
*, *::before, *::after {
    font-family: 'Roboto Flex', sans-serif;
}

components/drawer/index.vue

<template>
    <div class="drawer">
        drawer
    </div>
</template>

<style lang="scss">
@import './CDrawer.scss';
</style>

components/drawer/CDrawer.scss

.drawer {
    background: black;
}

I want to solve this problem because it makes work on the project more difficult. I can’t find a solution to the problem and I think the configuration is fine. Is he wrong? Thank you so much for your help

Javascript changing a specific element in a div

So I have something like this in my html:

<div id="basket">
    <div id="item">Apple</div>
</div>
<div id="basket">
    <div id="item">Orange</div>
</div>
<div id="basket">
    <div id="item">Banana</div>
</div>
// And so on

How would I be able to change the innerHTML of each ‘item’ div individually?
For example, how would I change the div that says ‘banana’ to something else?

my localhost does not render anything from react app

Im having trouble rendering in localhost, I was working on an old tutorial which had to make some changes and currently stuck on modifying my app.js and index.js to render in localhost, in the console.log it won’t show me any errors besides to edit my combine reducers unless that’s the problem I want to be able to see my app.js in. localhost and not a white screen.

app.js

import React, { useEffect } from 'react';
import {Container, AppBar, Typography, Grow, Grid} from '@material-ui/core';
import { useDispatch } from 'react-redux';

import { getPosts } from './actions/posts';
import Posts from './components/Posts/Posts';
import Form from './components/Form/Form';
import memories from './images/memories.png';
import useStyles from './styles';

const App = () => {
    const classes = useStyles();
    const dispatch = useDispatch();

useEffect(() => {
    dispatch(getPosts());
}, [dispatch]);

return (
    <Container maxidth="lg">
        <AppBar className={classes.AppBar} color="inherit">
            <Typography className={classes.heading} variant="h2" align='center'>Memories</Typography>
            <img className={classes.image} src={memories} alt="memories" height="1460" />
            <h1>hello</h1>
            
        </AppBar>
        <Grow in>
            <Container>
                <Grid container justify="space-between" alignitems="stretch" spacing={3}>
                    <Grid item xs={12} sm={7}>
                        <Posts />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                        <Form />
                    </Grid>
                </Grid>
            </Container>
        </Grow>
    </Container>
    
);
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { applyMiddleware, compose } from 'redux';
import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import reducers from './reducers';

import App from './App';

const store = configureStore(reducers, compose(applyMiddleware(thunk)));

ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root'),
  );

When the user closes the announcement don’t show notification to user again

I have created a notification bar on my site that I don’t want to be shown to users again on subsequent visits after they close it the first time. The bar works as expected, but I can’t seem to get the cookie to work to not display it again

js

$(document).ready(function(){
  $(".m-close").click(function(){
      $(".m-bar").hide(600);
  });
});

html code

<center>
  <div class="m-bar m-red">
    <a class="m-microphone"><i class="material-icons" style="font-size:26px;">mic</i></a>
    <a class="m-content" style="color: white;">Something Text</a>
    <a class="m-close" href="#"><i class="material-icons">close</i></a>
  </div>
</center> <br><br>

How to adjust this code in response to “Cannot set headers after they are sent to the client”? [duplicate]

In a controller I have the code below. This generates an error for the return at the the end:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
to the client

I understand this means I’m trying to return multiple times. But I don’t don’t understand this, since I have only one return. How can I solve this error?

const updatedUser = await user
    .update(updatedFields)
    .catch((error) => {
        return res.status(500).json({
            error: error.message,
        });
    });

            console.log(updatedUser);
            // prints: [object Object]
            console.log(JSON.stringify(updatedUser));
            // prints: TypeError: Converting circular structure to JSON

let userData = updatedUser;

userData = {
    ...userData.dataValues,
    userExpertise: req.body.userExpertise ? req.body.userExpertise : [],
    userRegions: req.body.userRegions ? req.body.userRegions : [],
};

            console.log(userData);
            // prints: [object Object]
            console.log(JSON.stringify(userData));
            // prints: {"userExpertise":[{"value":1,"label":"Finance"}],"userRegions":[{"value":3,"label":"Caribbean"}]}

return res.status(200).json({
    success: true,
    user: userData,
});

make a duplication of a branch with identical but not the same commits as of the original branch

I have this project added to a git repository with the main branch consisting of a number of commits.

      A--->B--->C--->D--->E

as i’m doing some experimental modifications on commits A through B i want to keep a copy of the commits of main branch inside a different branch main-copy in case anything went wrong due to play with commits in main branch and i wouldn’t want to go through restoring, i still have an intact copy of main branch.
if i create main_copy branch on top of commit E where Head is currently at i will not actually make a copy of main branch because commits A to B are common between the two branches.
so i need to create a branch on top of commit A and do the same commits in this branch. the final repository would be something like this.

     A--->B--->C--->D--->E
     |
     `--->B'--->C'--->D'--->E'

I have no idea how to do this without going back to commit A making another branch and doing commits B through E again one by one.
is there any devoted command to do this on git?

Angular search a key in an object and change the value of another key

I have this data below.
I need to be able to search in the objet for the id or name key and then change the ‘show’ key to a different value.
How example:

Search the data for id value 2 and change the show value to false.

data = [
   {
      id: 1,
      name: 'one',
      show: false;
      title: 'title1',
      data: [
         {
            id: 1,
            description: 'some description'
         },
         {
            id: 2,
            description: 'some other description'
         }
      ]
   },
   {
      id: 2,
      name: 'two',
      show: true;
      title: 'title2',
      data: [
         {
            id: 1,
            description: 'some description'
         },
         {
            id: 2,
            description: 'some other description'
         }
       ]
    }
 ]

How can I do this?

an empty object arrives in my backend server when i send from my frontend

An empty object arrives in my backend server when I send from my frontend.

My backend server should work fine as I tested it with postman. When I send the following JSON via postman I get a 200 response.

{“email”:”[email protected]”,”password”:”123456″}

I have a problem when I send the object via my frontend-code to my backend. The backend server crashes because it recieves an empty object. Why is that?

When i console.log enteredUsername, it’s not empty

console.log(enteredUsername, enteredPassword);
    let url = "http://localhost:4000/"
    fetch(url, {
      method: 'POST',
      body: JSON.stringify({
        email: enteredUsername,
        password: enteredPassword
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      mode: 'no-cors'
    }).then(res => {
        if (res.ok) {
          return res.json();
        } else {
          return res.json().then((data) => {
            let errorMessage = 'Authentication failed!';
            // if (data && data.error && data.error.message) {
            //   errorMessage = data.error.message;
            // }

            throw new Error(errorMessage);
          });
        }
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        alert(err.message);
      });
    
  }

This is the code from my backend server. When i console.log user, it’s empty

router.post('/', async (req,res)=>{
    console.log(req.body);
    const result = await data.addUser(req.body);
    res.send(result);
});

this is the method addUser:

async function addUser(user){
    const connectionDB = await connection.getConnection();
    
    console.log(user);
    user.password = bcrypt.hashSync(user.password,8);

    const result = await connectionDB.db('my-website')
        .collection('users')
        .insertOne(user);
    
    return result;
}

I get this error in my console of my browser:
POST http://localhost:4000/ net::ERR_CONNECTION_RESET

Thank you very much for helping me.

Unable to launch simple typescript + jquery project

I’m trying to setup a simple project using typescript and jquery, here you can find the code

https://github.com/anphetamina/simulator

When trying to launch a local server, for example using the Live Server extension from VSCode, I get the following error

Uncaught TypeError: Error resolving module specifier “@racehub-io/f1-telemetry-client”. Relative module specifiers must start with “./”, “../” or “/”.

Can you help me setup correctly this simple project? What’s wrong with the current one?

Use querySelectorAll to hide and disable classes

I’m attempting to adapt a solution that I found (here: https://stackoverflow.com/a/2155924/3394918) to a problem I’m having, and can’t seem to get it to work. I have several automatically generated menus with select elements that need to change based on user choices. In the linked question above, the user wanted to disable options based on values, however I want to disable (and enable) them based on class. I thought it would be an easy transition, but I haven’t been able to figure out what I’m doing wrong.

The original answer:

document.querySelectorAll("#foo option").forEach(opt => {
    if (opt.value == "StackOverflow") {
        opt.disabled = true;
    }
});

What I did with it:

document.querySelectorAll(".models1and2Option").forEach((option) => {
  option.disabled = true;
  option.hidden = true;
});

document.querySelectorAll(".model3Option").forEach((option) => {
  option.disabled = false;
  option.hidden = false;
});

Where each option has a class based on which user choice (model) it corresponds to. Example:

<option class="model3Option" disabled hidden value="Projected Revenue: Incentive Funding">Projected Revenue: Incentive Funding</option>

Not only is nothing changing when I test, when I console.log() document.querySelectorAll(“.model3Option”) the console says the NodeList is empty (but it’s not empty when I test other classes that aren’t attached to option elements), so I suspect I have a major error in my assumptions on how the code should be working.