Erro:SyntaxError: Missing initializer in const declaration - discord.js

i cant idendify the problem, please help.
usuário = user
acao = action/act
"Erro:SyntaxError: Missing initializer in const declaration"
const members = message.guild.members.cache.filter( m => m._roles.includes('762063845984174130'));
const mamado = usuário || member.get(Array.from(adms.keys())[Math.floor(Math.random() * member.size)]);
const ações = ['mamou graciosamente', 'mamou delicadamente', 'MORDEU', 'mamou como um profissional'];
const gifs = {
'mamou graciosamente': ['https://media1.tenor.com/images/7ef6a2fcaba846d7fc1ad99a9b952d5e/tenor.gif?itemid=4934925',
],
'mamou delicadamente': ['https://media1.tenor.com/images/37cf12caba4ebedfb6bafa4bcce5bab7/tenor.gif?itemid=10816189',
],
'MORDEU': ['https://pa1.narvii.com/5757/df946fe46d73864e6dd53143727549e1d0135a6e_00.gif'],
'mamou como um profissional': ['media1.tenor.com/images/76f9de536c5e20d278a507df28dfba4a/tenor.gif',
'https://media1.tenor.com/images/8decdf7fedc618aaa22b2f4cd8fba5d2/tenor.gif?itemid=14835705'],
};
const acao = ações[Math.floor(Math.random() * ações.length)];
const gif = gifs[acao][Math.floor(Math.random() * gifs[acao].length)];
const embed = new Discord.MessageEmbed()
.setDescription(`${message.author} ${acao} ${mamado}.`)
.setImage(gif)
.setFooter('ehehehehehehe'), message.client.user.avatarURL();
message.send({ embed: embed }).then(() => {
message.delete()
});

Related

Why formData does not take the data there is in the state and that has been refreshed, there is a delay character ? React

when i write in an input , i update the state (hook useState) and the state i put it in formData and the key ficheUser. With each keystroke the function where the setData and formData is located is executed.
But I notice that there is still a letter behind, there is a letter missing in formData compared to the state see the screenshot.
And I dont understand why ?
const changeHandler = (event) => {
const enteredNom = nomInputRef.current.value;
const enteredPrenom = prenomInputRef.current.value;
const enteredAge = ageInputRef.current.value;
console.log("------->event.target");
// console.log(event.target.files)
// console.log(event.target.files[0])
let newPhoto;
if (event.target.files && event.target.files.length === 1) {
newPhoto = event.target.files[0];
}
console.log("-->newPhoto");
console.log(newPhoto);
//Update the state
setDataUpdate(prevState => ({
...prevState.dataUpdate,
nom: enteredNom,
prenom: enteredPrenom,
age: enteredAge,
// newPhoto: newPhoto,
}));
//send new data to backend
const formData = new FormData();
formData.append("image", newPhoto);
formData.append("ficheUser", JSON.stringify(dataUpdate));
console.log("----->formData");
console.log(formData.get("image"));
console.log(formData.get("ficheUser"));
console.log("---------------");
const url = "http://localhost:3000/api/fiche_user/71?userId=92";
const fetchUploadHandler = async () => {
I am in self-training on React.js, I took the day to find the solution and it is very simple.
just take the values of the refs and put them in an object and especially not in useState and then put this object in formData... and it works there is no more delay letter
const changeHandler = (event) => {
const enteredNom = nomInputRef.current.value;
const enteredPrenom = prenomInputRef.current.value;
const enteredAge = ageInputRef.current.value;
//création de l'objet avec propriétés à envoyer dans formData
const dataUpdateFormData = {
nom: enteredNom,
prenom: enteredPrenom,
age: enteredAge,
};
console.log("--->dataUpdateFormData");
console.log(dataUpdateFormData);
//envoyer les nouvelles données vers le serveur
const formData = new FormData();
formData.append("image", newPhoto);
formData.append("ficheUser", JSON.stringify(dataUpdateFormData));
console.log("----->formData");
console.log(formData.get("image"));
console.log(formData.get("ficheUser"));
console.log("---------------");
const url = "http://localhost:3000/api/fiche_user/71?userId=92";
const fetchUploadHandler = async () => {

Cannot read property 'add' of undefined discord.js warm

Heres the code It was working when it was running on my pc but now i uploaded it to replit it gives me this error and idk how to fix it
Heres the full error
node:352) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined
at Object.run (/home/runner/PITOOOOOAOAOA/commands/moderation/warn.js:28:15)
at Client. (/home/runner/PITOOOOOAOAOA/index.js:97:13)
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const { Color } = require("../../config.js");
const db = require('quick.db');
module.exports = {
name: "warn",
aliases: [],
description: "Warnear A un Usurop!",
usage: "Warn <Mention User> | <Reason>",
run: async (client, message, args) => {
//Start
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.channel.send(
`No tienes permiso `
);
let Member =
message.mentions.members.first() ||
message.guild.members.cache.get(args[0]);
if (!Member) return message.channel.send(`Profavor menciona a Menciona a un usuario `);
let Reason = args.slice(1).join(" ");
client.db.add(`Warnings_${message.guild.id}_${Member.user.id}`,1);
let Warnings = client.db.get(
`Warnings_${message.guild.id}_${Member.user.id}`
);
let embed = new MessageEmbed()
.setColor(Color)
.setTitle(`Miembro Warneado! <a:686209726878449747:891459309987328041> `)
.addField(`Moderador`, `${message.author.tag} (${message.author.id}`)
.addField(`Miembro Warneado!`, `${Member.user.tag} (${Member.user.id})`)
.addField(`Now Member Warnings`, Warnings)
.addField(`Razon`, `${Reason || "No se proporcionó ninguna razón!"}`)
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send(embed);
//End
}
};
So i fixed it lol i didnt define the client.db all i had to do is change client.db to db and it worked
let Warnings = db.get(
`Warnings_${message.guild.id}_${Member.user.id}`
);

Problem trying to display a list of inputs when updating a record

I am practicing react with spring boot, I have a problem rendering inputs when I want to update the information
const {id} = useParams();
const dispatch = useDispatch();
const [inputList, setInputList] = useState([{id: '', mobileNumber: "", supplierNumber: id}]);
const history = useHistory();
//React Hook form estructura
const {register, handleSubmit, setValue, formState: { errors }} = useForm({resolver: yupResolver(schema)});
useEffect(() => {
//Si existe un id en el parametro de la url entonces realizamos el fetch
if(id) {
const fetchData = async () => {
try {
const resp = await axios.get(`${SUPPLIERS_ENDPOINT}/${id}`);
if(resp.data !== null) {
const {name, nif, email, webPage, mobileNumbers} = resp.data;
//Con estos setValues seteamos los values de los inputs del formulario, para que aparezcan rellenos con la informacion que nos devolvio el metodo get
setValue("name", name);
setValue("nif", nif);
setValue("webPage", webPage);
setValue("email", email);
*****I think the problem is here*************
mobileNumbers.map((m,i) => {
if(i !== 0) {
setInputList([...inputList, {id: m.id, mobileNumber: m.mobileNumber, supplierNumber: id}]);
} else {
setInputList([{id: m.id, mobileNumber: m.mobileNumber, supplierNumber: id}]);
}
});
}
} catch (error) {
setErrores(error);
console.log(error);
}
}
fetchData();
}
}, []);
The problem is that the useState only saves me the initial value and the last value of the setInputList.
Output:
but my desired output would be this
0: {id: 119, mobileNumber: 951, supplierNumber: "117"}
1: {id: 118, mobileNumber: 6789, supplierNumber: "117"}
Solved! it was just change to this in the useEffect:
mobileNumbers.forEach((m,i) => {
if(i !== 0) {
setMobNumsList(i => [...i, {id: m.id, mobileNumber: m.mobileNumber,supplierNumber:id}]);
} else {
setMobNumsList([{id: m.id, mobileNumber: m.mobileNumber, supplierNumber: id}]);
}
});

TypeError: Cannot convert undefined or null to object this occurs in a custom Hooks

Good evening community!
I'm currently getting this error when I attempt to use my custom hook.
This custom hook takes 3 parameters, an initial state, a validation rule, and an action function.
at the moment to validate my data appears as undefined.
//This is the custom Hook!
import React, { useState, useEffect } from 'react';
const useValidacion = (stateInicial, validar, fn) => {
const [ valores, guardarValores ] = useState(stateInicial);
const [ errores, guardarErrores ] = useState({});
const [ submitForm, guardarSubmitForm ] = useState(false);
useEffect(() => {
if(submitForm) {
const noErrores = Object.keys(errores).lenght === 0;
if(noErrores) {
fn(); //Funcion que se este ejecutando
}
guardarSubmitForm(false);
}
}, [errores])
// Funcion que se ejecuta cuando el usuario escribe
const handleChange = e => {
guardarValores({
...valores,
[e.target.name]: e.target.value
})
}
//Funcion que se ejecuta cuando el usuario da submit
const handleSubmit = e => {
e.preventDefault();
const erroresValidacion = validar(valores);
guardarErrores(erroresValidacion);
guardarSubmitForm(true);
}
return {
valores,
errores,
submitForm,
handleChange,
handleSubmit
}
}
export default useValidacion;
and these are the rules:
export default function validarCrearCuenta(valores) {
let errores = {};
// Validar el nombre
if(valores.nombre.trim() === '') {
errores.nombre = "El nombre es obligatorio"
}
// Validar el correo
if(!valores.email.trim() === '') {
errores.email = "El correo es obligatorio"
} else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(valores.email)) {
errores.email = "Correo no valido"
}
// Validar contraseña
if(!valores.password === '') {
errores.password = "La contraseña es obligatorio"
} else if(valores.password.lenght < 6) {
errores.password = "La contraseña debe ser de al menos 6 caracteres"
}
}
I would really appreciate help with this.
Does validar ever return null or undefined?
It's likely that errores becomes null or undefined at some point, probably when it is set to the return value of validar(valores) in handleSubmit.
Then we call Object.keys(null) in the useEffect, and that causes the error.
EDIT: Ah, yes I see the validar function is not returning a value. Just add return errores at the end.

Discord.js error, while selecting a random object from a another javascript

This is my code:
// index.js:
const Discord = require('discord.js');
const bot = new Discord.Client ();
const names = require('./names');
bot.on('message', message => {
if(message.content.toLowerCase() === '!randomname'){
const embed0 = new Discord.RichEmbed()
.setColor('#ba0f0f')
.setDescription("This is your random name: " + names.namelist[Math.floor(Math.random() * names.namelist.length)])
message.channel.send(embed0);
}
});
// names.js:
const namelist = [
'Oscar',
'John',
'Emma',
]
This is the error: Cannot read property 'length' of undefined (...names.namelist[Math.floor(Math.random() * names.namelist.length)]))
You need to export your array:
// array.js
const array = [
1,
2,
3
];
module.exports = array;
// main.js
const array = require('./array');
console.log(array.length);

Resources