set state after submit form in react js - html

how do you change the state back to blank when the form has been submitted?
I tried to empty it again when the form was submitted, but the state still has value
when it is finished, submit the state back to the initial state
state = {
importExcel: '',
active: true
};
handlerChange = e => {
this.setState({
importExcel: e.target.files[0],
active: !this.state.active
});
};
handlerOnSubmit = e => {
e.preventDefault()
const formData = new FormData();
formData.append('importExcel', this.state.importExcel);
api.post('web/user/import', formData)
.then(res => {
const { message, success } = res.data;
const alert = swal({
title: success === false ? 'Gagal Upload' : 'Berhasil Upload',
text: message,
icon: success === false ? 'error' : 'success',
// timer: 5000,
button: true
})
if (success === false) {
return alert
} else {
return alert
}
})
this.setState({
importExcel: '',
active: true
})
}

if (success === false) {
return alert
} else {
return alert
}
You are returning function every time. So the code below this line doesn't execute.

Related

How to display output in browser?

I retrieved my data from the database using the code below. It will return the number of "Active" and "Banned" account in console.log.
GetUserList = async user_type => {
this.setState({ loading: true });
const res = await userMgmt.getUserList(user_type);
console.log(res);
const activeAccount = res.data.data.filter(({ banned }) => !banned).length;
const bannedAccCount = res.data.data.filter(({ banned }) => banned).length;
console.log("Active : ", activeAccount);
console.log("Banned : ", bannedAccCount);
if (res.status === 200) {
if (this.mounted && res.data.status === "ok") {
this.setState({ loading: false, user_list: res.data.data });
}
} else {
if (this.mounted) {
this.setState({ loading: false });
}
ResponseError(res);
}
};
I want to display "activeAccount" and "bannedAccount" here but not sure how to.
const pageHeader = (
<PageHeader
style={{ backgroundColor: "#fff", marginTop: 4 }}
title="User Management - Admin"
<span>{`Banned User : `}</span>, //display banned here
<span>{`Active User : `}</span>, //display active here
/>
);
Insert both activeAccount and bannedAccCount into the state as follows.
const activeAccount = res.data.data.filter(({ banned }) => !banned).length;
const bannedAccCount = res.data.data.filter(({ banned }) => banned).length;
console.log("Active : ", activeAccount);
console.log("Banned : ", bannedAccCount);
if (res.status === 200) {
if (this.mounted && res.data.status === "ok") {
this.setState({
loading: false,
user_list: res.data.data,
activeAccount,
bannedAccCount,
});
}
}
Then show it inside the react component as follows.
const pageHeader = (
<PageHeader
style={{ backgroundColor: "#fff", marginTop: 4 }}
title="User Management - Admin"
<span>Banned User : {this.state.bannedAccCount}</span>, //display banned here
<span>Active User : {this.state.activeAccount}</span>, //display active here
/>
);

I am getting error sending status code in laravel apide

When sending response code in laravel api, validation does not enter.
I can view it from the network, but when I send the status code, the console prints an error and I cannot print the validations on the blade page. If I don't send status code I can print validations.
Following my code: StudentController
public function store(Request $request): object
{
$validate = Validator::make($request->all(),[
'name' => 'required',
'course' => 'required',
]);
$data = [
'name' => $request->name,
'course' => $request->course,
];
if ($validate->fails()){
return response()->json(['success' => false, 'errors' => $validate->messages()->all()],422);
}
Student::insert($data);
return response()->json(['success' => true, 'message' => "Registration Successful"]);
}
ajax
$(document).ready(function (){
$('#createBtn').on('click',function (e) {
e.preventDefault();
let form = $('#student-add').serialize();
$.ajax({
'url': "{{ route('students.store') }}",
'data': form,
'type': "POST",
success:function (result) {
$('#ajax-validate ul').text("");
if(result.success === true){
console.log("True");
}else {
result.errors.forEach(function (item) {
$('#ajax-validate ul').append('<li>'+item+'</li>');
});
}
}
});
});
});
console
network
You have your response.errors.forEach inside of your success: function(), but 422 (or any 400) code doesn't get handled by the success function, but rather the error function:
$(document).ready(function () {
$('#createBtn').on('click', function (e) {
e.preventDefault();
let form = $('#student-add').serialize();
$.ajax({
url: "{{ route('students.store') }}",
data: form,
type: 'POST',
success: function (result) {
if (result.success === true) {
// Do whatever on `2XX` HTTP Codes
}
},
error: function (response) {
if (response.status === 422) {
let responseJson = response.responseJSON ? response.responseJSON : { errors: [] };
$('#ajax-validate ul').text('');
responseJson.errors.forEach(function (item) {
$('#ajax-validate ul').append('<li>'+item+'</li>');
});
} else {
console.log('Unhandled Error:', response)
}
}
});
});
});
Now when an 422 error is explicitly triggered, you code can properly handle the validation errors.

Autodesk Forge Adding Input Element to Forge Button

I would like to dynamically add an input element to a button and based on Angular Binding, bind the input to the selected object in the viewer. What I tried so far you find below. The input element is shown without any problem. However, I cannot access the generated input element, no input possible.
Any suggestions to solve that?
public loadMobileToolbar() {
/////////////////////// Facade ///////////////////////
// #ts-ignore
var button1 = new Autodesk.Viewing.UI.Button('mobile-text-button-facade');
var button2 = new Autodesk.Viewing.UI.Button('mobile-coloring');
button1.onClick = (event) => {
console.log(this.input);
$('#mobile-text-button-facade').attr('data-before', '');
$('#mobile-text-button-facade').html('<input style="z-index: 100000" class="custom-input" type="text" [(ngModel)]="input.facade" (change)="onChange($event)" spellcheck="false">');
};
button2.onClick = (event) => {
this.showValuesOfParameter('facade');
};
button2.addClass('mobile-coloring');
// #ts-ignore
button2.container.children[0].classList.add('fas', 'fa-palette');
// Button 4 Textfeld
button1.addClass('mobile-text-button-facade');
// SubToolbar
var controlGroupMobile = new Autodesk.Viewing.UI.ControlGroup('mobile-custom-toolbar');
// controlGroupERP.addControl(button3);
controlGroupMobile.addControl(button1);
controlGroupMobile.addControl(button2);
this.toolbarMobile = new Autodesk.Viewing.UI.ToolBar('my-custom-view-toolbar-mobile-facade', {
collapsible: false,
alignVertically: false
});
this.toolbarMobile.addControl(controlGroupMobile);
$(this.viewerComponent.viewer.container)[0].append(this.toolbarMobile.container);
$('#mobile-text-button-facade').attr('data-before', 'Facade');
}
Adding the <input> without Angular bindings seems to be working fine:
You might need to ask around in the Angular community about the bindings.
var filterbox = new Autodesk.Viewing.UI.Filterbox('mobile-filterbox', { filterFunction: this.testing });
var controlGroupMobileInput = new Autodesk.Viewing.UI.ControlGroup('mobile-custom-toolbar-input');
controlGroupMobileInput.addControl(filterbox);
buttonFilter.onClick = (event) => {
if (!this.input.objectPath && this.viewerComponent.viewer.getSelectionCount() === 0) {
$('.filter-box.docking-panel-delimiter-shadow').val('');
button1.setState(1);
button7.setState(1);
// tslint:disable-next-line: no-use-before-declare
button3.setState(1);
// tslint:disable-next-line: no-use-before-declare
button9.setState(1);
// tslint:disable-next-line: no-use-before-declare
button5.setState(1);
$('#mobile-custom-toolbar-input').hide();
this.whichInput = '';
}
else if (this.viewerComponent.viewer.getSelectionCount() > 1 && this.redSelectedDbIDs.length === 0) {
this.multiSelectedMobileInput.forEach(input => {
if (this.whichInput === 'u' || this.whichInput === 'v') {
input[this.whichInput] = Number($('.filter-box.docking-panel-delimiter-shadow').val());
}
else if (this.whichInput === 'additionalParameter') {
input[this.whichInput][0].value = $('.filter-box.docking-panel-delimiter-shadow').val();
}
else {
input[this.whichInput] = $('.filter-box.docking-panel-delimiter-shadow').val();
}
});
this.api.saveMultipleInput(this.multiSelectedMobileInput).then(
res => {
if (res === null) {
this.messageService.add({ key: 'warning', severity: 'error', summary: 'Error', detail: 'Something went wrong with SAVING' });
}
else {
this.api.getAllInputs(this.platform.currentProject._id).then(
inputs => {
this.inputs = inputs;
// #ts-ignore
this.messageService.add({ key: 'warning', severity: 'success', summary: 'Success', detail: res.modified + ' INPUT was UPDATED', life: 5000 });
this.viewerComponent.viewer.clearThemingColors(this.viewerComponent.viewer.model);
this.editTable = false;
this.unsavedChanged = false;
}
);
}
}
);
this.multiSelectedMobileInput = new Array();
this.viewerComponent.viewer.clearSelection();
$('.filter-box.docking-panel-delimiter-shadow').val('');
button1.setState(1);
button7.setState(1);
// tslint:disable-next-line: no-use-before-declare
button3.setState(1);
// tslint:disable-next-line: no-use-before-declare
button9.setState(1);
// tslint:disable-next-line: no-use-before-declare
button5.setState(1);
$('#mobile-custom-toolbar-input').hide();
this.whichInput = '';
}
else if (this.redSelectedDbIDs.length !== 0) {
this.redSelectedDbIDs.forEach(dbId => {
this.viewerComponent.viewer.model.getProperties(dbId, (r) => {
var tempInput = this.inputs.find(ele => {
if (ele.objectPath.indexOf('/')) {
return ele.objectPath.split('/')[ele.objectPath.split('/').length - 1] === r.name;
}
else {
return ele.objectPath === r.name;
}
});
this.multiSelectedMobileInput.push(tempInput);
});
});
setTimeout(() => {
this.multiSelectedMobileInput.forEach(input => {
if (this.whichInput === 'u' || this.whichInput === 'v') {
input[this.whichInput] = Number($('.filter-box.docking-panel-delimiter-shadow').val());
}
else if (this.whichInput === 'additionalParameter') {
input[this.whichInput][0].value = $('.filter-box.docking-panel-delimiter-shadow').val();
}
else {
input[this.whichInput] = $('.filter-box.docking-panel-delimiter-shadow').val();
}
});
this.api.saveMultipleInput(this.multiSelectedMobileInput).then(
res => {
if (res === null) {
this.messageService.add({ key: 'warning', severity: 'error', summary: 'Error', detail: 'Something went wrong with SAVING' });
}
else {
this.api.getAllInputs(this.platform.currentProject._id).then(
inputs => {
this.inputs = inputs;
// #ts-ignore
this.messageService.add({ key: 'warning', severity: 'success', summary: 'Success', detail: res.modified + ' INPUT was UPDATED', life: 5000 });
this.viewerComponent.viewer.clearThemingColors(this.viewerComponent.viewer.model);
this.editTable = false;
this.unsavedChanged = false;
}
);
}
}
);

Vuejs- Get Object ID after POST Request In Current Page

I want to implement Save and Edit at same page. Of course, i have alot of field input so, i can Input a few input field and save Without Rediect to another page.
What i want is get current id after POST Request so, i can use That ID to PATCH request.
Vuejs Code
<v-btn
color="primary"
v-if="isEdit === false"
small
:loading="loading"
#click="save"
>save</v-btn
>
<v-btn
color="primary"
small
:loading="loading"
#click="edit"
v-if="isEdit === true"
>edit</v-btn
>
In script
<script>
export default {
data() {
return {
form: {},
isEdit: false
}
},
save() {
this.loading = true;
axios
.post(`api/v1/partner/`, this.form)
.then((res) => {
console.log(res);
this.isEdit = true;
})
.catch((err) => {
console.log(err.response);
this.loading = false;
this.snackbar.value = true;
this.$refs.form.validate(err.response.data);
});
},
edit() {
this.isEdit = true;
axios
.patch(`api/v1/partner/${this.form.id}/`, {
})
.then((res) => {
console.log(res);
// this.$router.push(`/partner/`);
this.loading = false;
})
.catch((err) => {
console.log(err.response);
this.loading = false;
});
},
}
</script>
I'll appreciate of all ur Help. Thanks...
Assuming your API responds from the POST request with the new ID, you can simply set it to your form object
axios.post("api/v1/partner/", this.form)
.then(res => {
console.log(res)
this.isEdit = true
this.form.id = res.data.id // assuming that's the right property name
})

How to use sweetalert2 preConfirm with httpRequest which needs to be subscribed to within Angular 9 component

I have an Angular form component which sends a http request and subscribes to that request. Now I'm trying to add a sweetalert2 feature to start a loader when the form is submitted (onSubmit()) and the http request is executed (with doSubmit()) and I'd like the sweetalert modal to change to a success or error message when http request returns a response which is subscribed to by the component (resulting in execution of onSuccess() or onError()). For some reason, my swal.preConfirm doesn't change the sweetalert from the loader to a success or error message. Can you please help?
protected doSubmit(): Observable<NewUser> {
swal.queue([{
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
},
preConfirm: () => {
return this.onSuccess()
.then(() =>
swal.insertQueueStep({
title: 'Success'
})
)
.catch(() =>
swal.insertQueueStep({
title: 'Error'
})
)
}
}])
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
}
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
onSuccess(){
return new Promise((resolve){
resolve('success')
})
onError(){
return new Promise((reject){
reject('error')
})
I figured out a bit of a make shift solution for this issue without using swal.preConfirm. Hopefully, there is a more elegant solution to achieving the same. For now, here's my solution:
protected doSubmit(): Observable<NewUser> {
this.invalidOnError = '';
this.navigationExtras = { queryParams: this.asssignToNavExtras.assignToNavExtras({ username: this.username.value }) };
swal.fire({
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
}
})
.then
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
};
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
protected onSuccess() {
swal.fire({
title: 'Registration Successful',
text: 'Thank you',
icon: 'success',
confirmButtonText: 'OK',
buttonsStyling: false,
customClass: {
confirmButton: 'btn'
},
timer: 10000,
})
}
protected onError() {
swal.fire({
showConfirmButton: false,
timer: 10,
onAfterClose: () => {
code for where to place focus after sweetalert is closed
}
})
}