On button click clear displayed text and call another function in VueJs - html

I'm fairly new to web development and vue.js.
I have an app where I enter an Id in and on button(search) click it is calling a method. This method makes an axios call to the controller and retrieves data as an object.
This data is displayed in tag (not sure if this approach is correct).
After this data is displayed, when the second time I enter another Id in the field and hit the button, it still displays the old text till it fetches the new data. Once new data is retrieved, it displays the new one.
I want to clear this data everytime I hit the button for search as well as call the vue function to fetch data.
I have tried clearing the data at the beginning of the vue function call but that didn't work.
<input type="text" placeholder="Enter the ID" v-model="mId" />
<button type="button" class="searchgray" v-on:click="SubmitId">Search</button>
<h4 style="display: inline">ID: {{queryData.Id}}</h4>
<strong>Device Status: </strong><span>{{queryData.deviceStatus}}</span>
<script>
export default {
components: {
'slider': Slider,
Slide
},
props:['showMod'],
data() {
return {
mId '',
queryData: {},
}
},
methods: {
SubmitId: function () {
this.queryData = {}
axios.get('/Home/SearchId?Id=' + this.mId)
.then(response => response.data).then(data => {
this.queryData = data
}).catch(err => {
this.queryData = {}
this.mId = ''
alert(`No records found anywhere for the given mId`)
});
}
}
</script>
So in the above code, when I hit the Search button, it calls the SubmitId function and returns queryData. Now when I enter a new mId in input field and hit serach button it continues to display the querydata associated with the old mId till the fetching of data is completed and new query data for the new mId is returned.
I was looking for a way to clear the screen text everytime I hit the button. So I also tried doing queryData={} before the axios call, but it didn't help.
Help appreciated.

new Vue({
el: '#app',
props: [
'showMod'
],
data() {
return {
mId: '',
queryData: {}
}
},
methods: {
async SubmitId () {
const axiosRequest = () => new Promise((resolve, reject) => {
const obj = {
Id: Math.random(),
deviceStatus: Math.random()
}
setTimeout(() => {
resolve(obj)
// reject('Not Found')
}, 2000)
})
try {
this.queryData = {}
this.queryData = await axiosRequest()
} catch (err) {
this.mId = ''
alert('No records found anywhere for the given mId')
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input
v-model="mId"
type="text"
placeholder="Enter the ID"
/>
<button
v-on:click="SubmitId"
type="button"
class="searchgray"
>
Search
</button>
</br>
<h4 style="display: inline">
ID: {{ queryData.Id }}
</h4>
</br>
<strong>Device Status: </strong>
<span>{{ queryData.deviceStatus }}</span>
</div>

Related

Storing Multiple Form submission containing multiple inputs with React

I am building a signup form containing multiple inputs(username, date of birth, etc). After a form is submitted it is stored somewhere containing a list of previous submitted forms.
Link to working sample: https://codesandbox.io/s/react-form-multiple-storage-xcmt3i?file=/src/App.js
Codebase for working sample:
import React, { useState } from "react";
const App = () => {
const [values, setValues] = useState({
userName: "",
dateOfBirth: ""
});
const [submissions, setSubmission] = useState([
{
userName: "april123",
dateOfBirth: "2000-01-01"
}
]);
const addSubmission = (values) => {
const newSubmissions = [...submissions, { values }];
setSubmission(newSubmissions);
console.log(submissions);
};
const handleChange = (event) => {
const value = event.target.value;
setValues({
...values,
[event.target.name]: value
});
};
const handleSubmit = (event) => {
event.preventDefault();
addSubmission(values);
};
return (
<>
<form onSubmit={handleSubmit}>
<h1> Signup Form </h1>
<div>
<label>username</label>
<input
type="text"
name="userName"
onChange={handleChange}
value={values.userName}
required
/>
</div>
<div>
<label>Date of Birth</label>
<input
type="date"
name="dateOfBirth"
onChange={handleChange}
value={values.dateOfBirth || ""}
/>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</>
);
};
export default App;
Questions:
Is addSubmission setup properly for what I am trying to achieve? Or can it be improved?
Base on console.log() placement, why am I only seeing previous submissions and not current? Screenshot below for details.
Your addSubmission isn't consistent, you initialize it as an array of Objects, but when you add a submission to it you are adding an extra value key, as seen in your second log, where the value at index 1 is an object with a key of value. To resolve this, simply remove the bracket
const newSubmissions = [...submissions, values];
You should also clear the current state values after you have successfully submitted an entry.
SetState is async, which means React might still be updating the state when your console.log is called, and that's why you wouldn't see the current submission, if you place the console.log outside of the function and have it triggered on rerender you would see the new submission.

How do I send data from HTML to my a var in my component in angular 6

I am making an app where you are suppose to be able to edit notes but I am str <textarea class="form-control displayNoteTextAreaD" >{{notesService.ActiveNote.note}}</textarea> - this is displaying the current note I have in the database.
<button (click)="saveNote()" class="button" >Save Note</button>
When I click this button I want to save the new data in a var.
I dont want it to be two way binding.
I have a note: String = "" in my component
This is saveNote()
saveNote(){
const note = {
title: this.notesService.ActiveNote.title,
note: (the new note),
type: this.notesService.ActiveNote.type,
voice: this.notesService.ActiveNote.voice,
user_id: this.userServices.ActiveUser.id,
id: this.notesService.ActiveNote.id
}
const _note: Note = new Note(note);
console.log(_note);
this.notesService.updateUserNote(_note).subscribe(data => {
console.log(data);
})}
Edit your textarea this way:
<textarea #tarea value="" class="form-control displayNoteTextAreaD" >{{notesService.ActiveNote.note}}</textarea>
Add this to your button:
<button (click)="saveNote(tarea.value)" class="button" >Save Note</button>
your saveNote function should be like this:
saveNote(noteValue){
const note = {
title: this.notesService.ActiveNote.title,
note: noteValue, // <------
type: this.notesService.ActiveNote.type,
voice: this.notesService.ActiveNote.voice,
user_id: this.userServices.ActiveUser.id,
id: this.notesService.ActiveNote.id
}
const _note: Note = new Note(note);
console.log(_note);
this.notesService.updateUserNote(_note).subscribe(data => {
console.log(data);
})}

Vuejs component does not render immediately

I have a vue app and a component. The app simply takes input and changes a name displayed below, and when someone changes the name, the previous name is saved in an array. I have a custom component to display the different list items. However, the component list items do not render immediately. Instead, the component otems render as soon as I type a letter into the input. What gives? Why would this not render the list items immediately?
(function(){
var app = new Vue({
el: '#app',
components: ['name-list-item'],
data: {
input: '',
person: undefined,
previousNames: ['Ian Smith', 'Adam Smith', 'Felicia Jones']
},
computed: {
politePerson: function(){
if(!this.person) {
return 'Input name here';
}
return "Hello! To The Venerable " + this.person +", Esq."
}
},
methods: {
saveInput: function(event){
event.preventDefault();
if(this.person && this.previousNames.indexOf(this.person) === -1) {
this.previousNames.push(this.person);
}
this.setPerson(this.input);
this.clearInput();
},
returnKey: function(key) {
return (key + 1) + ". ";
},
clearInput: function() {
this.input = '';
},
setPerson: function(person) {
this.person = person;
}
}
});
Vue.component('name-list-item', {
props: ['theKey', 'theValue'],
template: '<span>{{theKey}} {{theValue}}</span>'
});
})()
And here is my HTML.
<div id="app">
<div class="panel-one">
<span>Enter your name:</span>
<form v-on:submit="saveInput">
<input v-model="input"/>
<button #click="saveInput">Save</button>
</form>
<h1>{{politePerson}}</h1>
</div>
<div class="panel-two">
<h3>Previous Names</h3>
<div>
<div v-for="person, key in previousNames" #click='setPerson(person)'><name-list-item v-bind:the-key="key" v-bind:the-value="person" /></div>
</div>
</div>
</div>
You are not defining your component until after you have instantiated your Vue, so it doesn't apply the component until the first update.

Chrome Dev Tools: How to simulate offline for a particular domain than the entire network?

Use case?
Firebase has a new product Firestore, that enables offlinePersistence as per their documentation.
https://firebase.google.com/docs/firestore/manage-data/enable-offline?authuser=0#listen_to_offline_data
I want to test a situation, where the app loads, but there is no connection made to firebase (think of Progressive Web App with cached static assets by serviceworker), but no network to connect to Firebase.
My code looks like
import React from "react";
import {fdb} from "../mainPage/constants";
// includeDocumentMetadataChanges to know when backend has written the local changes
// includeQueryMetadataChanges to know if changes come from cache using 'fromCache' property
// https://firebase.google.com/docs/firestore/manage-data/enable-offline?authuser=0#listen_to_offline_data
const queryOptions = {
includeDocumentMetadataChanges: true,
includeQueryMetadataChanges: true
};
const collectionName = "todos";
export default class ToDos extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
textBox: "",
loading: true
}
}
componentWillMount() {
let unsubscribe = fdb.collection(collectionName)
.onSnapshot(queryOptions, function (querySnapshot) {
let items = [];
querySnapshot.forEach(function (doc) {
items.push(doc);
//console.log(" data: ", doc && doc.data());
});
this.setState({"items": items});
}.bind(this));
this.setState({"unsubscribe": unsubscribe});
}
componentWillUnmount() {
this.state.unsubscribe();
}
handleTextBoxChange = (event) => {
this.setState({textBox: event.target.value});
};
handleAddItem = () => {
fdb.collection(collectionName).add({
"title": this.state.textBox
}).then(function (docRef) {
//console.log("added " + docRef.id, docRef.get());
});
};
handleRemoveItem = (item) => {
console.log("Deleting: ", item.id);
item.ref.delete()
.then(function () {
console.log(item.id + " deleted successfully");
})
.catch(function(reason){
console.log(item.id + " failed to delete: ", reason);
})
};
render() {
return (
<div>
<div>
<input type="text" value={this.state.textBox} onChange={this.handleTextBoxChange}/>
<input type="submit" value="Add Item" onClick={this.handleAddItem}/>
</div>
<div>{this.state.items
.map((item, index) => <Item key={index}
item={item}
onDeleteClick={this.handleRemoveItem}/>)}</div>
</div>
)
}
}
const Item = ({item, onDeleteClick}) => {
let pendingWrite = item.metadata.hasPendingWrites ? "[PendingWrite]" : "[!PendingWrite]";
let source = item.metadata.fromCache ? "[Cache]" : "[Server]";
return <div>
<input type="button" value="delete" onClick={() => onDeleteClick(item)}/>
<span>{source + " " + pendingWrite + " " + item.data().title}</span>
</div>
};
Question
Is there a way in Chrome Developers Tool, to simulate/disable calls to a specific domain?
You are looking for the "Request Blocking" feature. To use this go to the overflow menu, then "More Tools", then click on "Request Blocking". This opens the proper panel in the drawer to block requests to a certain domain or resource.
Finding the menu item.
The request blocking panel.

How to reset ReactJS file input

I have file upload input:
<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/>
And I handle upload this way:
getFile(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (theFile) => {
var data = {
blob: theFile.target.result, name: file.name,
visitorId: this.props.socketio.visitorId
};
console.log(this.props.socketio);
this.props.socketio.emit('file-upload', data);
};
reader.readAsDataURL(file);
}
If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?
I think you can just clear the input value like this :
e.target.value = null;
File input cannot be controlled, there is no React specific way to do that.
Edit For old browsers (<IE11), you can use one of the following techniques.
See http://jsbin.com/zurudemuma/1/edit?js,output (tested on IE10 & 9)
What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:
functionThatResetsTheFileInput() {
let randomString = Math.random().toString(36);
this.setState({
theInputKey: randomString
});
}
render() {
return(
<div>
<input type="file"
key={this.state.theInputKey || '' } />
<button onClick={this.functionThatResetsTheFileInput()} />
</div>
)
}
That forces React to render the input again from scratch.
This work for me - ref={ref => this.fileInput = ref}
<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
then in my case once the file was uploaded to the server , I clear it by using the statement below
this.fileInput.value = "";
I do it by updating key inside my file input.
This will force a re-render and previously selected file will go away.
<input type="file" key={this.state.inputKey} />
Changing the state inputKey will re-render the component.
One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.
With every click onClick you can reset the input, so that even with the same file onChange will be triggered.
<input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
import React, { useRef } from "react";
export default function App() {
const ref = useRef();
const reset = () => {
ref.current.value = "";
};
return (
<>
<input type="file" ref={ref} />
<button onClick={reset}>reset</button>
</>
);
}
The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.
TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.
NOTE: I also included how I reset a text input in case anyone else was curious.
function CreatePost({ user }) {
const [content, setContent] = React.useState("");
const [image, setImage] = React.useState(null); //See Supporting Documentation #1
const imageInputRef = React.useRef(); //See Supporting Documentation #2
function handleSubmit(event) {
event.preventDefault(); //Stop the pesky default reload function
setContent(""); //Resets the value of the first input - See #1
//////START of File Input Reset
imageInputRef.current.value = "";//Resets the file name of the file input - See #2
setImage(null); //Resets the value of the file input - See #1
//////END of File Input Reset
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add Post Content"
onChange={event => setContent(event.target.value)}
value={content} //Make this input's value, controlled by state
/>
<input
type="file"
onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
/>
<button type="submit">Submit Form</button>
</form>
</div>
)
};
Supporting Documentation:
useState Hook
Returns a stateful value, and a function to update it.
useRef Hook
If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
Using files from web apps
If the user selects just one file, it is then only necessary to consider the first file of the list.
You can also include this in your input element if you know you are not going to be using the built-in file input value at all.
<input value={""} ... />
This way the value is always reset to the empty string on render and you don't have to include it awkwardly in an onChange function.
I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.
constructor(props) {
super(props);
this.state = {
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.removeImage = this.removeImage.bind(this);
}
handleChange(event) {
if (event.target.files[0]) {
this.setState({
selectedFile: event.target.files[0],
selectedFileName: event.target.files[0].name,
imageSrc: window.URL.createObjectURL(event.target.files[0]),
value: event.target.value,
});
}
}
// Call this function to reset input
removeImage() {
this.setState({
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
})
}
render() {
return (
<input type="file" value={this.state.value} onChange={this.handleChange} />
);
}
We can reset file input by using key = {this.state.fileInputKey} and initialsing fileInputKey to Date.now() in constructor state.
On file upload success , we need to again assign fileInputKey: Date.now(), so it will have different value than previous and it create new file input component on next render()
We can also do this manually by clicking button to clear/reset file Input
Below is the working code :
import React from "react";
import { Button } from "reactstrap";
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
fileInputKey: Date.now(),
message: ""
};
this.handleClear = this.handleClear.bind(this);
this.onClickHandler = this.onClickHandler.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
onChangeHandler = event => {
this.setState({
selectedFile: event.target.files
});
};
onClickHandler = () => {
if (this.state.selectedFile === null) {
this.setState({
message: "Please select File"
});
return;
}
//axios POST req code to send file to server
{
/**
const data = new FormData()
data = this.state.selectedFile[0]
axios.post("http://localhost:8080/api/uploadFile/", data)
.then(res => {
if (res.status == 200) {
// upload success
}
})
.catch(err => {
//message upload failed
})
*/
}
//after upload to server processed
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: "File Uploaded"
});
};
handleClear() {
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: ""
});
}
render() {
return (
<div>
<input
type="file"
key={this.state.fileInputKey}
class="form-control"
onChange={this.onChangeHandler}
/>
<button
type="button"
class="btn btn-success btn-block"
onClick={this.onClickHandler}
>
Upload
</button>
<Button
type="button"
value="Clear"
data-test="clear"
onClick={this.handleClear}
>
{" "}
Clear{" "}
</Button>
<br />
<label>{this.state.message}</label>
</div>
);
}
}
export default FileUpload;
Here is my solution using redux form
class FileInput extends React.Component {
constructor() {
super();
this.deleteImage = this.deleteImage.bind(this);
}
deleteImage() {
// Just setting input ref value to null did not work well with redux form
// At the same time just calling on change with nothing didn't do the trick
// just using onChange does the change in redux form but if you try selecting
// the same image again it doesn't show in the preview cause the onChange of the
// input is not called since for the input the value is not changing
// but for redux form would be.
this.fileInput.value = null;
this.props.input.onChange();
}
render() {
const { input: { onChange, value }, accept, disabled, error } = this.props;
const { edited } = this.state;
return (
<div className="file-input-expanded">
{/* ref and on change are key properties here */}
<input
className="hidden"
type="file"
onChange={e => onChange(e.target.files[0])}
multiple={false}
accept={accept}
capture
ref={(input) => { this.fileInput = input; }}
disabled={disabled}
/>
{!value ?
{/* Add button */}
<Button
className="btn-link action"
type="button"
text="Add Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
:
<div className="file-input-container">
<div className="flex-row">
{/* Image preview */}
<img src={window.URL.createObjectURL(value)} alt="outbound MMS" />
<div className="flex-col mg-l-20">
{/* This button does de replacing */}
<Button
type="button"
className="btn-link mg-b-10"
text="Change Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
{/* This button is the one that does de deleting */}
<Button
type="button"
className="btn-link delete"
text="Delete Image"
onPress={this.deleteImage}
disabled={disabled}
/>
</div>
</div>
{error &&
<div className="error-message"> {error}</div>
}
</div>
}
</div>
);
}
}
FileInput.propTypes = {
input: object.isRequired,
accept: string,
disabled: bool,
error: string
};
FileInput.defaultProps = {
accept: '*',
};
export default FileInput;
In my case I had a functional component and after selecting a file it suppose to set the file name in the state so using any solution above was failing except the ref one which i fixed like this.
const fileUpload = props => {
const inputEl = useRef(null)
const onUpload = useCallback(e => {
uploadFile(fileDetails)
.then(res => {
inputEl.current.value = ''
})
.catch(err => {
inputEl.current.value = ''
})
})
return (
<input type='file' ref={inputEl} onChange={handleChange} />
<Button onClick={onUpload}>Upload</Button>
)
}
I recently got stumbled into this issue to reset the File type input field. I think it is still a milestone for most developers. So I thought I should share my solution.
Since we are listening to the onChange event to update the image file into some of our states, we will have our component rerendered once we set the state. In such case, we can specify the value of the input file as empty like value='' which will cause the input field to reset its value after each change of its value.
<input
type="file"
value=''
onChange={onChangeFnc}
/>