Trying to handle errors with axios with React state and sweetalert2 - reactjs

I've tried this a few different ways and can't seem to get it to work.
I am trying to handle an error when a user enters an already existing username. The backend works fine, however I am trying to get sweetalert to respond appropriately
front end react jsx
const [errors, setErrors] = useState({
error: false,
message: ''
});
const saveUser = async(userData) =>{
await axios.post('/save_score', userData).then((res)=>{
if(res.status === 200){
Swal.fire({
icon: 'success',
title: 'Score saved!',
text: `${res.data.username} scored ${res.data.score} points`,
showCancelButton: true,
cancelButtonText: 'Hiscores',
confirmButtonText: 'Play again'
})
}
}).catch((err)=>{
if(err.response.status === 400){
setErrors({
error: true,
message: err.response.data.usernameError
})
}
});
}
const gameOver = (score) => {
Swal.fire({
title: 'Game over',
text: `You scored ${score} points! Save your score?`,
allowOutsideClick: false,
showConfirmButton: true,
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then((response)=>{
if(response.isConfirmed){
//user confirmed
Swal.fire({
title: 'Enter your username',
input: 'text',
inputLabel: 'Username: ',
showCancelButton: true,
inputValidator: (value) => {
if(!value){
return 'Must enter a username!';
} else {
var userData = {username: value, score: score};
saveUser(userData).then(()=>{
console.log(errors);
})
}
}
})
} else {
console.log('user cancelled');
}
})
}
the problem I've been having with this specific attempt is that the state isn't changing. when I log after my saveUser().then(), the state comes back as its initialized even when I am trying to throw the username exists error.
I've also tried creating an error object, and inside the axios post's error, I set that objects error key to true and the errors response to that objects message key, but when that happens it seems axios post comes after any sort of error handling and it doesn't respond correctly.
let me know if this is enough info

Related

Problem: DiscordAPIError: Unknown Message [10008]

I'm currently trying to make a purge command right now (following reconlx's Purge Command tutorial for DJS v13), and I keep receiving a DiscordAPI Error.
The command only works once, however, it doesn't reply with embeds like it's supposed to, then crashes along with every other command there is. It does become functional again after a certain period of time then the cycle repeats over and over again.
I have made sure that I had the right intents (which I do) and such, but nothing seems to work... I have no idea what in the world is causing the error. Anyone who would be willing to help is doing me a favour.
Oh, and here's the code for purge.js and the error in question down below.
const { MessageEmbed } = require("discord.js");
const ms = require("ms");
module.exports = {
name: "purge",
description: "Purges messages",
userPermissions: ["MANAGE_MESSAGES"],
options: [
{
name: "amount",
description: "Amount of messages to purge",
type: "INTEGER",
required: true,
},
],
run: async (client, interaction) => {
const amount = interaction.options.getInteger("amount");
const limitEmbed = new MessageEmbed()
.setColor("#2F3136")
.setTitle("You may only purge 100 messages at a time!")
.setFooter({ text: "Error: Limit Reached" })
if (amount > 100)
return interaction.followUp({
embeds:
[limitEmbed],
});
const messages = await interaction.channel.messages.fetch({
limit: amount + 1,
});
const filtered = messages.filter(
(msg) => Date.now() - msg.createdTimestamp < ms("14 days")
);
await interaction.channel.bulkDelete(filtered)
const successEmbed = new MessageEmbed()
.setColor("#2F3136")
.setTitle(`Successfully purged ${filtered.size - 1} messages!`)
.setFooter({ text: "Action Successfully Performed" })
interaction.followUp({
embeds:
[successEmbed],
});
},
};
Error:
DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\admin\Desktop\Tonkotsu\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (C:\Users\admin\Desktop\Tonkotsu\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async InteractionWebhook.send (C:\Users\admin\Desktop\Tonkotsu\node_modules\discord.js\src\structures\Webhook.js:196:15) {
method: 'post',
path: '/webhooks/950050048618688572/aW50ZXJhY3Rpb246OTk5MjYyNTIyMTc3NzQ5MDAzOmhGaUJVQkF6YjduVUlZNTJsT1MwV254T2FYdEJiaUNMWDdwUWloYzhyNnJudERLMHhxak96RTlkTmpDQW5sdEhONnhKSGkyZkdlQndmWGJQSFM0dk52bGduZ3hBTlE3S3g4R2JBRWFRdDNEbmtrb3Z6a0hpVk8yU2hIYllyemhm?wait=true',
code: 10008,
httpStatus: 404,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [
{
title: 'Successfully purged 3 messages!',
type: 'rich',
description: null,
url: null,
timestamp: 0,
color: 3092790,
fields: [],
thumbnail: null,
image: null,
author: null,
footer: {
text: 'Action Successfully Performed',
icon_url: undefined
}
}
],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
You should use interaction.reply(...) instead of interaction.followUp(...), followUp is used when you already replied to a message and want to continue replying to the interaction. So it will throw an error if you trying to use it on an interaction who hasn't been replied yet.

Buttons: Interaction has already been acknowledged

I'm trying to disable the button after a certain amount of clicks
But when I click that amount of times, it doesn't update and I get an error saying interaction has already been acknowledged.
I tried it without the i.reply but I keep getting interaction failed.
client.buttonClicks = 0;
message.channel.send({
content: "Click on the button below to enroll for fate adventure!",
components: [row],
});
const filter = (m) => m.customId === "enrollButton";
const collector = message.channel.createMessageComponentCollector({
filter: filter,
max: parseInt(args[1]),
time: 15000,
});
collector.on("collect", async (i) => {
await i.reply({
content: "`You have enrolled in the fate adventure`",
ephemeral: true,
});
message.channel.send(`<#${i.user.id}> *enrolls in the fate adventure.*`);
client.buttonClicks++;
if (client.buttonClicks == args[1]) {
row.components[0].setDisabled(true);
await i.update({
content: "**Maximum Members reached**",
components: [row],
});
message.channel.send("done");
}
});
collector.on("end", (collected) => {
message.channel.send(`Clicked ${collected.size} times`);
});

I'm a beginner in programming and I'm trying to use axios.post, but the error [object Object] is returning, I don't know where I'm going wrong

API body:
{
"title":"Cortar a grama",
"description":"Manutenção em áreas verdes de até 1000 metros quadrados.",
"price":40,
"paymentMethods":["PayPal", "boleto"],
"dueDate":"2021-12-30"
}
Below part of the code:
state = {
title: "",
description: "",
price: "",
paymentMethods: [],
dueDate: "",
}
changeTitle = (e) => {
this.setState({ title: e.target.value })
}
changeDescription = (e) => {
this.setState({ description: e.target.value })
}
changePrice = (e) => {
this.setState({ price: e.target.value })
}
changePaymentMethods = (e) => {
this.setState({ paymentMethods: e.target.value })
}
changeDueDate = (e) => {
this.setState({ dueDate: e.target.value })
}
registerService = (event) => {
event.preventDefault()
const body = {
title: this.state.title,
description: this.state.description,
price: this.state.price,
paymentMethods: this.state.paymentMethods,
dueDate: this.state.dueDate
}
axios.post(baseUrl, body, axiosConfig)
.then(() => {
alert('Oferta de serviço cadastrada com sucesso')
}).catch(err => {
alert(err.response.data)
console.log(err.response.data)
})
this.setState({
title: "",
description: "",
price: "",
paymentMethods: [],
dueDate: ""
})
}
Something is failing in your axios.post call and you are not being able to read the error correctly. I guess you are getting [Object Object] error on your alert function, but your console.log is probably displaying your error correctly.
I'd say that there's something wrong with your url or config.
You may try do do some things to investigate this error:
1 - Try the POST action on Postman, if you know how to use it;
2 - Check the api docs to verify if you don't nedd specific credentials to post it of if something is missing;
3 - Change your alert
alert(err.response.data);
to:
alert(err);
or if you want the data object:
alert(JSON.stringify(err.response.data));
4 - Change your console.log to console.dir, this would giive you access to the attributes of the object
console.dir(err.response.data); // or console.dir(err);
Doing these steps could help you to understand what is failing on your request and correct the issue.

CastError: Cast to ObjectId failed for value "{ _id: ':5ec5cc919efcf581eb692690' }" at path "_id" for model "Posts"

Checking the router on the server side it console logs the right values, only the follow error is popping up in here. Trying to build a counter that should update the value on the backend. But the problem I have is that value will not be stored in there. When using Postman the value will be stored successfully. What is the solution that can fix this issue.
export const incrementProduct = (index, updateAmount, id) => {
return dispatch => {
dispatch(increment(index));
try {
axios.patch(`${API_URL}/:${id}`, {
amount: updateAmount
}).then(res => {
console.log(res.config);
})
} catch(err) {
console.log(err)
}
}
}
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
amount: {
type: Number,
required: true
},
editable: {
type: Boolean,
required: true
},
data: {
type: Date,
default: Date.now
}
});
// update
router.patch('/:postId', async(req, res) => {
console.log('update', req.params.postId + 'amount ' + req.body.amount)
try {
const updatedPost = await Post.findByIdAndUpdate(
{_id: req.params.postId}, <--- this cause the console error...
{$set:
{
amount: req.body.amount
},
})
console.log('try')
res.json(updatedPost)
} catch(err) {
console.log(err + 'test ')
res.json({ message: err })
}
})
You need to remove : in the patch url like this:
axios.patch(`${API_URL}/${id}`
Also findByIdAndUpdate requires only the value of _id, so you can only pass the value like this:
await Post.findByIdAndUpdate(req.params.postId, ...
findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

How to prevent from form submission when email exists error and how to set value in form itself without getting reset

The below code shows the form submit function. the form gets submitted but when email exist error occurs the form gets reset. how to prevent form getting reset?.
submit = values => {
// print the form values to the console
let formValues = {
clu_first_name: values.clu_first_name,
clu_last_name: values.clu_last_name,
clu_email: values.clu_email,
clu_sec_email: " ",
// "clu_state":0,
// "clu_city":0,
// "clu_zip":0,
// "clu_address":null,
clu_contact: values.clu_contact,
lgn_password: values.clu_pass,
cli_id: client_id, // SRM id
cat_id: values.cat_id,
dep_id: values.dep_id,
usr_id: usr_ID,
clu_id: values.clu_id
};
console.log("formValues-fmp", formValues);
let decodeFormValues = { json: JSON.stringify(formValues) };
this.setState({ formSubmitting: true });
fetch(
`${Utils.getApiBaseUrl()}/fmp/client/addClientUser`,
Utils.getPostOptions(decodeFormValues)
)
.then(response => {
return response.json();
})
.then(res => {
if (res.status == 1) {
toast.success(" Successfully created.", {
position: toast.POSITION.TOP_RIGHT,
autoClose: 3000
});
this.fetchUserList(client_id);
this.setState({ formSuccess: true, formError: false, opened: false });
} else {
toast.error("Email exists", {
position: toast.POSITION.TOP_RIGHT,
autoClose: 3000
});
this.setState({
formError: true,
formSuccess: false,
errorText: res.data
});
}
this.setState({ formSubmitting: false });
});
};
Below is my form code, here because of onsubmitsuccess it get reset, I want to get reset after success if any error occurs the form must have the values.
const afterSubmit = (result, dispatch) => dispatch(reset("createuser"));
CreateUserForm = reduxForm({
form: "createuser",
multipartForm: true,
onSubmitSuccess: afterSubmit
})(CreateUserForm);

Resources