Is it possible to send multiple data in one view on Node JS?

I am trying to pass several data to one view. I can send the products to it but I would like to send the categories as well. I want to send them separately and not with a join. I have been advised to put it after the “then” but I don’t know how to do it.

router.get('/', function (req, res) {
  models.produit.findAll(
    {
      include: 
      [
        {
          model: models.image, as: "images" 
        },
        {
          model: models.promotionproduit, as: "promotionproduits",
          include:[{model: models.promotion, as: "Promotion"}]
        }
      ]})
      .then(data => {
        res.render('home', {
          data: data
        });
      
    }).catch(err => console.log(err));
});

React Router ComponentDidMount Not Executing

I need to have the componentDidMount method to fire when the Router mounts a component so that a timeout can be started. This timeout eventually sets the state so it can’t be initialized in any render lifecycles or the constructor. I tried changing the Route’s component={Home} to render={<Home>}, but then the error render is not a function comes up. I’m really not sure why this is happening so any help would be greatly appreciated!

App.js render method:

render() {
  return (
    <BrowserRouter>
      <Navbar />
      <Container>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/about" component={About} />
        </Switch>
      </Container>       
    </BrowserRouter>
  );
}

Home.js:

const Home = (props) => {
  const images = [ /* Stuff */ ];

  return (
    <Stack gap={4}>
      <div>
        <Card>
          <Card.Header>
            <ImageRotator images={images} />
          </Card.Header>
          <Card.Body>
            <Card.Title>// A Title</Card.Title>
            <Card.Text>
              // Text
            </Card.Text>
          </Card.Body>
        </Card>
      </div>
    </Stack>
  );
}

ImageRotator.js:

class ImageRotator extends Component {
  constructor(props) {
    super(props);

    this.state = {
      firstImageIndex: 0,
      renderImages: false,
      imagesShowing: [],
    }
  }

  componentDidMount() {
    const imagesShowing = this.calculateImagesToShow(this.state.firstImageIndex);
    this.setState({ imagesShowing: imagesShowing });

    window.addEventListener('resize', () => { 
      const imagesToShow = this.calculateImagesToShow(this.state.firstImageIndex);
      const imageTimeout = setTimeout(() => this.incrementImageIndex(), 5000);
      this.setState({ imagesShowing: imagesToShow, imageTimeout: imageTimeout });
    });
  }

  calculateImagesToShow(firstImageIndex) {
    // Returns the images to render on screen
  }

  resetImageInterval() {
    clearTimeout(this.state.imageInterval);
    this.setState({ imageInterval: setTimeout(() => this.incrementImageIndex(), 5000) });
  }

  incrementImageIndex() {
    // Increments the state's first image index
  }

  decrementImageIndex() {
    // Decrements the state's first image index
  }

  render() {
    // Renders the calculated images on the screen including two buttons
    // which when clicked on call the increment and decrement image index functions
  }
}

Block scope in relation to global variables

Assuming I need to use global variable for some script:(example)

<script>
let myVAR=0;
// some functions
......
......
</script>

Is the following code good for preventing use of global variable? (for my understanding,this is called Block scope,If I’m wrong please clarify me). Second,Is this bad practice or it’s not? If it is,Is there another method to replace global variable?(My target is to access multiple functions in the script with unknown amount of uses,with onclick events,onkeyup events,etc..)

<script>
{
let myVAR=0;
// some functions
......
......
}
</script>

Javascript – remove sub-objects in an object of arrays of objects by key value

I have a javascript object containing an array of other objects, like the following:

const myObj = {
  people: [{
      firstname: 'Dave',
      lastName: 'Jones',
      sortOrder: 22
    },
    {
      firstname: 'Jane',
      lastName: 'Smith',
      sortOrder: 11
    }
  ],
  otherPeople: [{
      firstname: 'Jen',
      lastName: 'SomeLastName',
      sortOrder: 33
    },
    {
      firstname: 'ExampleFirstName',
      lastName: 'ExampleLastName',
      sortOrder: 12
    }
  ]
};

What I’m trying to do is, given a certain number, let’s say 2, remove that amount of sub objects with the highest sortOrder.

So if I were to eliminate 2, the new object would look like the following:

const myObj = {
  people: [{
      firstname: 'Jane',
      lastName: 'Smith',
      sortOrder: 11
    }
  ],
  otherPeople: [{
      firstname: 'ExampleFirstName',
      lastName: 'ExampleLastName',
      sortOrder: 12
    }
  ]
};

Is there a best way to do this?

Thanks!

How to navigate through a list

I want to render all the ‘name’ elements inside ‘rotas’, but when i try it says map is undefined. Maybe it’s a newbie question but i just can’t figure out how to do this, any help is apreciated.

export default function SelecionaRota(props) {
    const data = {
        locais: [
            {
                name: 'Rio de Janeiro',
                rotas: [
                    {
                        name: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        name: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (
        <div>
            <h1>{estadoOrigem}</h1>
            { rota.locais.rotas.map(module => (
                <h1>{module.nome}</h1>
            ))}
        </div>
    )
}

How to display data from DB with JS in HTML site

I want to display data in a paragraph in a HTML file using JS. I have the following codes:

the button:

<button class = "buttonClickMe" onClick="showData();">Show Data</button>
<p>Here we will show some data</p>
<p id = "demo"></p>

the function to show data:

function showData(){
    sql = `SELECT * FROM MyTable`;
    
    db.all(sql, [], (err, rows)=>{
        rows.forEach((row)=>{
            console.log = row;
        })
    })
}

i tried displaying it using this code that i found

document.getElementById("demo").addEventListener("click", myFunction);

function myFunction() {   document.getElementById("demo").innerHTML = "this works"; }

But when i put the showData() function on the place of “this works” or change MyFunction, it says that “showData()” doesn’t return. When I write it without () it still doesn’t work. But it works when it is only “this works”

document.getElementById("demo").addEventListener("click", myFunction //doesnt work when using showData here//);

function myFunction() {
  document.getElementById("demo").innerHTML = "text"//doesnt work when using showData here//;
}

I tried using return statement in showData(), but I am not sure how I should return the data.

¿Existe una función para convertir un ‘Undefined’ a String en JavaScript? [closed]

El frontend manda los valores requeridos al backend para hacer un post en mi base de datos, en este caso es agregar un usuario, pero no se porque el backend recibe la variable del celular como ‘undefined’ cuando debe de ser String, entonces quiero saber si hay alguna manera de convertir este campo a String para poder guardarlo correctamente en mi base de datos.

Este es mi código en el backend (JavaScript):

rutas.post('/' (req, res) => {})
    const{nombre, apellido, correo, cel, usuario, contra} = req.body

    // Esta parte es para verificar como se estaban recibiendo los datos
    let celular = req.body.cel;
    console.log(req.body);
    console.log("celular: "+ celular);
    console.log("tipo: "+ typeof(celular));

    let sql = `INSERT INTO usuarios(nombre_us, apellido_us, correo_us, cel_us, usuario_us, contra_us) `+
              `VALUES('${nombre}', '${apellido}', '${correo}', '${cel}', '${usuario}', '${contra}')`
    conexion.query(sql, (error, filas, campos) => {
        if(error) throw error;
        else
        {
            res.json({status: 'Usuario agregado'})
        }
    });
});

Y esto es lo que me muestra en consola:

enter image description here

Executing Prisma query in loop: Promise { }

My code:

const getStats = async (projects) => {
  return projects.map(async (project) => {
    const count = await db.ping.count({
      where: { projectId: project.id },
    })
    console.log("Result is: " + count)
    return count
  })
}

The return value (there are two different projects, so two elements are correct):

[ Promise { <pending> }, Promise { <pending> } ]

If I understand that correctly, my outer promise when I call the function gets resolved correctly. Hence the array itself is not wrapped in a Promise. However, my two values still seem to be wrapped in a promise. The weird thing is that the console.log calls output the correct count number for each project, without any Promises:

Result is: 8
Result is: 1

Can anyone help me out here?

PUT request from React through superagent being sent with no content

The method sending the request looks like this:

const updateCompany = ({sessionKey},company) => {
    const tempCompany = company.newCompany;
    console.log("sessionkey:" + sessionKey);
    console.log("check123" + JSON.stringify(tempCompany,getCircularReplacer()));
    const url = createServiceUrl(`api/company/${sessionKey}/${tempCompany.id}`);
    request
        .put(url)
        .send({ Company: tempCompany })
        .end((err, res) => {
            if (res.ok) {
                console.log("Updated OK!")
            }
        });
}

The check123 console.log prints the object I’m trying to send with all the expected values and keys, but for some unknown reason the request going out is completely empty and all I get back from the controller is a 204. I suppose I’m supposed to do something differently here, but I can’t see what.

React-Native Firestore – Get user info for a comment section

I’m building an app using react-native and react-native-firebase and i’m running into an issue while trying to implement a comment section.

My tree of data is currently like that :
collection(comments)/doc(currentUser.uid)/collection(userComments)/doc(commentCreatorID)

Within this doc commentCreatorID there is all the data i need. So basically the content, a timestamp…

For this part everything works perfectly but in order to havethe commentCreator’s infos stick with his post, i need to grab them somewhere else.
The way i do that is taking the doc(commentCreatorID), as it is the uid of this user and ask firestore to give me the data from the document with this same id within my “users” collection.

Here is my code :

  const [comments, setComments] = useState([])
  const [commentsReady, setCommentsReady] = useState([])

useEffect(() => {

        setComments([])
        setLoading(true)
        firestore()
        .collection('comments')
        .doc(auth().currentUser.uid)
        .collection('userComments')
        .get()
        .then((snapshot) => {
            let comments = snapshot.docs.map(doc => {
                const data = doc.data()
                const id = doc.id
                return {id, ...data}
            })
            setComments(comments)
        })
        .then(() => {
            comments.forEach(comment => {
                firestore()
                .collection("users")
                .doc(comment.id)
                .get()
                .then((snapshot) => {
                    const data = snapshot.data()
                    setCommentsReady({comments, ...data})       
                })
            })
        })
       console.log(commentsReady)
        setLoading(false)
    }, [handleScroll4])

This doesn’t seem to works well as for now. My log throw an empty array right into my face..
I’m grabbing each comment correctly tho and even each user’s data corresponding to their uids.
I can log them once ForEach have been done.
But for some reason i can’t have them set to my state commentsReady.

Did i miss something ?

Thanks for your time

How to edit an embed?

I cannot edit an embed that is already posted, here is my code :

const c = client.channels.cache.get('919237216692215829')
const m = c.messages.cache.get('919675014633095179')
const embed = new MessageEmbed()
//embed..
m.edit(embed)

console:

m.edit(embed)
  ^

TypeError: Cannot read property 'edit' of undefined```

Excute Javascript when order status is changed in the back-end

I am trying to execute a JavaScript file for when the order status is changed in the back-end. But it doesn’t seem to work. Below is the code I am currently using. Can anybody tell me what I am doing wrong? When I try to enqueue the script in other places, it does work.

function script_on_order_complete( $order_id ) {
    wp_register_script('test', get_template_directory_uri() .'/js/test.js',false);
    wp_enqueue_script( 'test');
}
add_action( 'woocommerce_order_status_completed', 'script_on_order_complete', 10, 1 );

Changing the size of a with the value of fetched data

I am fetching data from an api and display some props of them using mapping and I want to change the width of the accordingly with the value of the props.

<h5>
    <span className="viewcount" ref={boxSize}>
    {`View Count: ${item.statistics.viewCount}`}</span>
</h5>

For example, this is a prop called “viewcount” from the api item, and I want the width of this component to be 200px when the viewcount prop is a number of 200.
How can I acheive it?

P.S.: I’m using react.

How to attach user credentials to the request pipeline in expressjs?

I am trying to write a middleware that extracts the user model and attach it to the request pipeline.
I have already written a token extractor middleware and managed to attach the token to the request pipeline, but for some reason when I try to extract the user model, it works fine inside the middleware function yet inside my controller it returns as undefined.

Here’s what I have tried:

utils/middleware.js

const tokenExtractor = async (request, response, next) => {    
        const authorization = await request.get('authorization');
       if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
         request.token = authorization.substring(7);         
       } else{
         request.token = null;
        }
        next();
};

const userExtractor = async (request, response, next) => {  
  tokenExtractor(request, response, next);
  if(request.token){
    const decodedToken = jwt.verify(request.token, process.env.SECRET);    
    request.user = await User.findById(decodedToken.id);
    console.log(request.user); // Works
    next();
  } else{
    response.status(403).json({ error: 'no token received' });
  }
};

Inside my controllers it breaks down:

controllers/blogs.js

blogRouter.post("/", async (request, response, next) => {
  if (request.body.title && request.body.url) {
    const token = request.token;    
    if (!token) {
      return response.status(401).json({ error: 'invalid token' });
    }
      
    console.log(request.user); // undefined !
    if(!request.user){
      return response.status(401).json({ error: 'invalid user' });
    }
    
    const user = request.user;    
    
    const blog = new Blog({
      title: request.body.title,
      author: request.body.author,
      url: request.body.url,
      likes: request.body.likes,
      user: user._id,
    });

    
    await blog.save();    
    
    user.blogs = user.blogs.concat(blog._id);
    await user.save();
    
    response.status(201).json(blog);
  }
  response.status(400).end();
});

Both middleware are already attached to the express app.