clear input box on certain condition react - javascript

I am making a get request to a quiz api. When the user gets the answer correct the next answer is shown.
This is all working well, however I have got into some trouble when trying to clear the input box when the user gets the answer correct. I read this earlier and as far as I can tell it should be following the same logic.
Can anyone spot what is wrong here?
var Quiz = React.createClass({
getInitialState: function() {
return {
question: '',
answer: '',
value: '',
score: 0
}
},
getData: function() {
$.get('http://jservice.io/api/random', function(data){
var response = data[0];
console.log(response)
this.setState({
question: response.question,
answer: response.answer
})
}.bind(this));
},
componentDidMount: function() {
this.serverRequest = this.getData()
},
checkAnswer: function(event) {
if(event.target.value.toLowerCase() === this.state.answer.toLowerCase()) {
this.setState({
score: this.state.score + 1,
value: ''
})
this.getData();
}
},
skipQuestion: function() {
this.getData();
},
render: function() {
var value = this.state.value
return (
<div>
<p>{this.state.question}</p>
<input type='text' value={value} onChange={this.checkAnswer}/>
<p onClick={this.skipQuestion}>New question</p>
<p>{this.state.score}</p>
</div>
)
}
});

I moved this code into a jsbin and your input clearing logic is working fine. However, as #finalfreq mentioned in your implementation it's impossible to type a full answer in to the input box, each input gets recognized but is never displayed. The fix for that is shown below. The only change is adding the else case in checkAnswer:
var Quiz = React.createClass({
getInitialState: function() {
return {
question: '',
answer: '',
value: '',
score: 0
}
},
getData: function() {
$.get('http://jservice.io/api/random', function(data){
var response = data[0];
console.log(response)
this.setState({
question: response.question,
answer: response.answer
})
}.bind(this));
},
componentDidMount: function() {
this.serverRequest = this.getData()
},
checkAnswer: function(event) {
if(event.target.value.toLowerCase() === this.state.answer.toLowerCase()) {
this.setState({
score: this.state.score + 1,
value: ''
})
this.getData();
} else {
this.setState({
value: event.target.value.toLowerCase()
})
}
},
skipQuestion: function() {
this.getData();
},
render: function() {
var value = this.state.value
return (
<div>
<p>{this.state.question}</p>
<input type='text' value={value} onChange={this.checkAnswer}/>
<p onClick={this.skipQuestion}>New question</p>
<p>{this.state.score}</p>
</div>
)
}
});

Related

V-model is not listening to value change for an input (vuejs)

I have an object property which could listen to the user input or could be changed by the view.
With the snipped below :
if I typed something the value of my input is updated and widget.Title.Name is updated.
if I click on the button "External Update", the property widget.Title.Name is updated but not the value in my field above.
Expected result : value of editable text need to be updated at the same time when widget.Title.Name change.
I don't understand why there are not updated, if I inspect my property in vue inspector, all my fields (widget.Title.Name and Value) are correctly updated, but the html is not updated.
Vue.component('editable-text', {
template: '#editable-text-template',
props: {
value: {
type: String,
default: '',
},
contenteditable: {
type: Boolean,
default: true,
},
},
computed: {
listeners() {
return { ...this.$listeners, input: this.onInput };
},
},
mounted() {
this.$refs["editable-text"].innerText = this.value;
},
methods: {
onInput(e) {
this.$emit('input', e.target.innerText);
}
}
});
var vm = new Vue({
el: '#app',
data: {
widget: {
Title: {
Name: ''
}
}
},
async created() {
this.widget.Title.Name = "toto"
},
methods: {
externalChange: function () {
this.widget.Title.Name = "changed title";
},
}
})
button{
height:50px;
width:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<editable-text v-model="widget.Title.Name"></editable-text>
<template>Name : {{widget.Title.Name}}</template>
<br>
<br>
<button v-on:click="externalChange">External update</button>
</div>
<template id="editable-text-template">
<p ref="editable-text" v-bind:contenteditable="contenteditable"
v-on="listeners">
</p>
</template>
I searched a lot of subject about similar issues but they had reactivity problem, I think I have a specific problem with input. Have you any idea of what's going on ? I tried to add a listener to change event but it was not triggered on widget.Title.Name change.
To anwser to this problem, you need to do 3 differents things.
Add watch property with the same name as your prop (here value)
Add debounce function from Lodash to limit the number of request
Add a function to get back the cursor (caret position) at the good position when the user is typing
For the third point : when you change the value of widget.Title.Name, the component will re-render, and the caret position will be reinitialize to 0, at the beginning of your input. So, you need to re-update it at the last position or you will just write from right to left.
I have updated the snippet above with my final solution.
I hope this will help other people coming here.
Vue.component('editable-text', {
template: '#editable-text-template',
props: {
value: {
type: String,
default: '',
},
contenteditable: {
type: Boolean,
default: true,
},
},
//Added watch value to watch external change <-> enter here by user input or when component or vue change the watched property
watch: {
value: function (newVal, oldVal) { // watch it
// _.debounce is a function provided by lodash to limit how
// often a particularly expensive operation can be run.
// In this case, we want to limit how often we update the dom
// we are waiting for the user finishing typing his text
const debouncedFunction = _.debounce(() => {
this.UpdateDOMValue();
}, 1000); //here your declare your function
debouncedFunction(); //here you call it
//not you can also add a third argument to your debounced function to wait for user to finish typing, but I don't really now how it works and I didn't used it.
}
},
computed: {
listeners() {
return { ...this.$listeners, input: this.onInput };
},
},
mounted() {
this.$refs["editable-text"].innerText = this.value;
},
methods: {
onInput(e) {
this.$emit('input', e.target.innerText);
},
UpdateDOMValue: function () {
// Get caret position
if (window.getSelection().rangeCount == 0) {
//this changed is made by our request and not by the user, we
//don't have to move the cursor
this.$refs["editable-text"].innerText = this.value;
} else {
let selection = window.getSelection();
let index = selection.getRangeAt(0).startOffset;
//with this line all the input will be remplaced, so the cursor of the input will go to the
//beginning... and you will write right to left....
this.$refs["editable-text"].innerText = this.value;
//so we need this line to get back the cursor at the least position
setCaretPosition(this.$refs["editable-text"], index);
}
}
}
});
var vm = new Vue({
el: '#app',
data: {
widget: {
Title: {
Name: ''
}
}
},
async created() {
this.widget.Title.Name = "toto"
},
methods: {
externalChange: function () {
this.widget.Title.Name = "changed title";
},
}
})
/**
* Set caret position in a div (cursor position)
* Tested in contenteditable div
* ##param el : js selector to your element
* ##param caretPos : index : exemple 5
*/
function setCaretPosition(el, caretPos) {
var range = document.createRange();
var sel = window.getSelection();
if (caretPos > el.childNodes[0].length) {
range.setStart(el.childNodes[0], el.childNodes[0].length);
}
else
{
range.setStart(el.childNodes[0], caretPos);
}
range.collapse(true);
sel.removeAllRanges();
}
button{
height:50px;
width:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<editable-text v-model="widget.Title.Name"></editable-text>
<template>Name : {{widget.Title.Name}}</template>
<br>
<br>
<button v-on:click="externalChange">External update</button>
</div>
<template id="editable-text-template">
<p ref="editable-text" v-bind:contenteditable="contenteditable"
v-on="listeners">
</p>
</template>
you can use $root.$children[0]
Vue.component('editable-text', {
template: '#editable-text-template',
props: {
value: {
type: String,
default: '',
},
contenteditable: {
type: Boolean,
default: true,
},
},
computed: {
listeners() {
return {...this.$listeners, input: this.onInput
};
},
},
mounted() {
this.$refs["editable-text"].innerText = this.value;
},
methods: {
onInput(e) {
this.$emit('input', e.target.innerText);
}
}
});
var vm = new Vue({
el: '#app',
data: {
widget: {
Title: {
Name: ''
}
}
},
async created() {
this.widget.Title.Name = "toto"
},
methods: {
externalChange: function(e) {
this.widget.Title.Name = "changed title";
this.$root.$children[0].$refs["editable-text"].innerText = "changed title";
},
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app">
<editable-text v-model="widget.Title.Name"></editable-text>
<template>Name : {{widget.Title.Name}}</template>
<br>
<br>
<button v-on:click="externalChange">External update</button>
</div>
<template id="editable-text-template">
<p ref="editable-text" v-bind:contenteditable="contenteditable" v-on="listeners">
</p>
</template>
or use Passing props to root instances
Vue.component('editable-text', {
template: '#editable-text-template',
props: {
value: {
type: String,
default: '',
},
contenteditable: {
type: Boolean,
default: true,
},
},
computed: {
listeners() {
return {...this.$listeners, input: this.onInput
};
},
},
mounted() {
this.$refs["editable-text"].innerText = this.value;
this.$root.$on("titleUpdated",(e)=>{
this.$refs["editable-text"].innerText = e;
})
},
methods: {
onInput(e) {
this.$emit('input', e.target.innerText);
}
}
});
var vm = new Vue({
el: '#app',
data: {
widget: {
Title: {
Name: ''
}
}
},
async created() {
this.widget.Title.Name = "toto"
},
methods: {
externalChange: function(e) {
this.widget.Title.Name = "changed title";
this.$root.$emit("titleUpdated", this.widget.Title.Name);
},
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app">
<editable-text v-model="widget.Title.Name"></editable-text>
<template>Name : {{widget.Title.Name}}</template>
<br>
<br>
<button v-on:click="externalChange">External update</button>
</div>
<template id="editable-text-template">
<p ref="editable-text" v-bind:contenteditable="contenteditable" v-on="listeners">
</p>
</template>

Vue 2 component prop getting wrong value

I am trying to build a menu between categories. If a category has a sub-category it returns a value that says has_subCategory as boolean 0/1.
<template>
<select><slot></slot></select>
</template>
<script>
export default {
props: ['value',
'hasSubCat'],
watch: {
value: function(value, hasSubCat) {
this.relaod(value);
this.fetchSubCategories(value, hasSubCat);
}
},
methods: {
relaod: function(value) {
var select = $(this.$el);
select.val(value || this.value);
select.material_select('destroy');
select.material_select();
},
fetchSubCategories: function(value, hasSubCat) {
var mdl = this;
var catID = value || this.value;
var has_subCat = hasSubCat || this.hasSubCat;
console.log("has_subCat:" + has_subCat);
mdl.$emit("reset-subcats");
if (catID) {
if (has_subCat == 0) {
if ($('.subdropdown').is(":visible") == true) {
$('.subdropdown').fadeOut();
}
} else {
axios.get(URL.API + '/subcategories/' + catID)
.then(function(response) {
response = response.data.subcatData;
response.unshift({
subcat_id: '0',
subcategory_name: 'All Subcategories'
});
mdl.$emit("update-subcats", response);
$('.subdropdown').fadeIn();
})
.catch(function(error) {
if (error.response.data) {
swal({
title: "Something went wrong",
text: "Please try again",
type: "error",
html: false
});
}
});
}
} else {
if ($('.subdropdown').is(":visible") == true) {
$('.subdropdown').fadeOut();
}
}
}
},
mounted: function() {
var vm = this;
var select = $(this.$el);
select
.val(this.value)
.on('change', function() {
vm.$emit('input', this.value);
});
select.material_select();
},
updated: function() {
this.relaod();
},
destroyed: function() {
$(this.$el).material_select('destroy');
}
}
</script>
<material-selectcat v-model="catId" name="category" #reset-subcats="resetSubCats" #update-subcats="updateSubCats" id="selcat">
<option v-for="cat in cats" :value="cat.cat_id" :hasSubCat="cat.has_subCat" v-text="cat.category_name"></option>
</material-selectcat>
The data looks like this:
cat_id:"0"
category_name:"All Subcategories"
has_subCat:0
What I dont understand is that console.log("has_subCat:" + hasSubCat); prints out different values each time I change the select. It should only display 0 or 1
Watcher in vue.js is supposed to be used in order to watch one value, but you can fulfill your requirement with help of computed.
export default {
props: ['value',
'hasSubCat'],
watch: {
/* without this, watcher won't be evaluated */
watcher: function() {}
},
computed: {
watcher: function() {
this.reload(this.value);
this.fetchSubCategories(this.value, this.hasSubCat);
}
},
...
}
I also made a simplified working fiddle, you can have a look.
You are assuming that the second parameter of your watch function is hasSubCat which is not the case. While the first parameter of the value watch function represents the new value of the property, the second parameter is actually the old value of the watched property. Try this out to understand more.
watch: {
value: function(value, oldValue) {
console.log('new value:', value)
console.log('old value:', oldValue)
}
}
So to watch both of value and hasSubCat, you can do something like this:
watch: {
value: function(newValue) {
this.reload(newValue)
this.fetchSubCategories(newValue, this.hasSubCat)
},
hasSubCat: function(newHasSubCat) {
this.reload(this.value)
this.fetchSubCategories(this.value, newHasSubCat)
}
}

How to wait to render view in react.js until $.get() is complete?

Hello I'm writing a chat client in reactjs and want to render my components with data retrieved from a REST call. However, my component is rendered before the REST request returns with data; this causes errors as I am calling this.props within my children components.
var MainChat = React.createClass({
getInitialData: function(){
var c = []
$.get("http://127.0.0.1:8888/test/sampledata.php?user=123", function(data, status) {
console.log("Data: "+ data+ "\nStatus: " + status);
c = data
})
},
getInitialState: function() {
return {
chatId : "",
chats : this.getInitialData(),
//chats: this.props.chats
};
},
handleClickOnLeftUser: function(data){
console.log("handleClickOnLeftUser");
// console.log("chat id is");
// console.log(data.chatID);
this.setState({chatID: data.chatID});
},
render: function() {
console.log("main:render")
console.log(this.props.chats);
var theThreadIWantToPass = {};
for(var i = 0; i < this.state.chats.length; i++)
{
console.log("chat: " + this.state.chats[i].chatID);
if (this.state.chats[i].chatID === this.state.chatID) {
theThreadIWantToPass = this.state.chats[i];
break;
}
}
return (
<div className="chatapp">
<div className="thread-section">
<div className="thread-count">
</div>
<LeftUserList
chats={this.state.chats}
clickFunc={this.handleClickOnLeftUser} // ***important
/>
</div>
<div>
<RightMessageBox chat={theThreadIWantToPass} />
</div>
</div>
);
}
});
In your case you need use method componentDidMount, like so
var MainChat = React.createClass({
getInitialData: function() {
var url = 'http://127.0.0.1:8888/test/sampledata.php?user=123';
$.get(url, function(data, status) {
this.setState({ chats: data });
}.bind(this))
},
componentDidMount: function () {
this.getInitialData();
},
getInitialState: function() {
return {
chatId: '',
chats: []
};
},
handleClickOnLeftUser: function(data){
this.setState({ chatID: data.chatID });
},
render: function() {
var theThreadIWantToPass = {};
for(var i = 0; i < this.state.chats.length; i++) {
if (this.state.chats[i].chatID === this.state.chatID) {
theThreadIWantToPass = this.state.chats[i];
break;
}
}
return (
<div className="chatapp">
<div className="thread-section">
<div className="thread-count"></div>
<LeftUserList
chats={this.state.chats}
clickFunc={this.handleClickOnLeftUser} />
</div>
<div>
<RightMessageBox chat={theThreadIWantToPass} />
</div>
</div>
);
}
});
Note - using "async": false this is bad practice
Found a hackish fix for the time being (at least until someone answers). My current solution is to prevent jQuery from using callbacks by setting
$.ajaxSetup({ "async": false})
before I call Jquery's get() function.
getInitialData: function(){
var c = []
$.ajaxSetup({ "async": false})
$.get("http://127.0.0.1:8888/test/sampledata.php?user=123", function(data, status) {
console.log("Data: "+ data+ "\nStatus: " + status);
c = data
})
return c
},
getInitialState: function() {
return {
chatId : "",
chats : this.getInitialData(),
//chats: this.props.chats
};
},

React filtering data error: this.props.updateFilter is not a function

I'm trying to implement a filter for an image list that works as you type and getting the above error. I think it's to do with the way I've mapped the data I'm importing, but can't figure it out. I'm still learning React.
var Filters = React.createClass({
handleFilterChange: function() {
var value = this.refs.filterInput.getDOMNode().value;
this.props.updateFilter(value);
},
render: function() {
return <input type="text" ref="filterInput" onChange={this.handleFilterChange} placeholder="Filter" />;
}
});
/** #jsx React.DOM */
var ListItem = React.createClass({
render: function() {
return (
<li className="col-lg-3" style={listStyle}>
<h2>{this.props.filename}</h2>
<p><img className="img-thumbnail" src={this.props.photoLink}/></p>
<p>
<small>Camera model: <strong>{this.props.model}</strong></small><br/>
<small>Camera make: <strong>{this.props.make}</strong></small>
</p>
</li>
)
}
});
var ListContainer = React.createClass({
loadNotificationsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: this.state.data.concat([data])});
clearInterval(this.interval);
}.bind(this)
});
},
getInitialState: function() {
return {
data: [],
nameFilter: ''
};
},
componentWillMount: function() {
this.loadNotificationsFromServer();
this.interval = setInterval(this.loadNotificationsFromServer, this.props.pollInterval);
},
render: function() {
if (this.state.data) {
return (
<div>
{this._hasData()}
</div>
)
} else {
return <div>Loading...</div>;
} return false
},
_handleFilterUpdate: function(filterValue) {
this.setState({
nameFilter: filterValue
});
},
_hasData: function() {
var data = this.state.data.map(function(item) {
return item.works.work;
});
if (data.length > 0) {
var imageDetails = _.map(data[0], function(result, n, key){
var image = _(result.urls.url).find({'_type': 'small'});
return {
id: result.id,
filename: result.filename,
_type: image ? image._type : null,
url: image ? image.__text : null,
model: result.exif.model,
make: result.exif.make
};
}, []);
var listItems = imageDetails.map(function(result, index){
return <ListItem key={index}
filename={result.filename}
photoLink={result.url}
model={result.model}
make={result.make} />
})
return listItems
} else return false
}
});
// INITIALISE PAGE
var imageList= React.createClass({
render: function() {
/* component composition == function componsition */
return (
<div>
<Filters updateFilter={this._handleFilterUpdate} />
<ListContainer url="/scripts/works.json" pollInterval={2000}/>
</div>
);
}
});
module.exports = imageList;

Do something once, then every 15 seconds in react js

I have the following code:
var Panel = React.createClass({
getInitialState: function () {
return {
user_id: null,
blogs: null,
error: false,
error_code: '',
error_code: ''
};
},
shouldComponentUpdate: function(nextProps, nextState) {
if (nextState.error !== this.state.error ||
nextState.blogs !== this.state.blogs ||
nextState.error_code !== this.state.error_code
) {
return true;
}
},
componentDidMount: function() {
var self = this;
var pollingInterval = setInterval(function() {
$.get(self.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_code: '',
error_message: '',
blogs: result.user.blogs,
user_id: result.user.id
});
}
}.bind(self)).fail(function(response) {
self.setState({
error: true,
error_code: response.status,
error_message: response.statusText
});
}.bind(self));
}, 1000);
},
render: function() { ... }
});
The important part to focus on is the componentDidMount This will fetch every second, regardless if there is an error or not. The render function, assuming theres an error, will display the appropriate method. So for all intense and purpose, this code does exactly what I want it to do, it fetches, if it fails, it fetches again until it succeeds.
But I need to make some changes, and this is where I am lost. I want to say: Fetch once, pass or fail - it doesn't matter. THEN every 15 seconds after that initial fetch, try again - regardless of pass or fail
I would normally spin up a backbone collection and router along with a poll helper to do all this, but in this specific case there is no need for the extra overhead. So thats where I am stumped. How do I accomplish what I am trying to achieve?
You should be able to just refactor your code a bit to be able to call your polling function a few different ways (like manually for example and then at a specified interval):
componentDidMount: function() {
this.startPolling();
},
componentWillUnmount: function() {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
},
startPolling: function() {
var self = this;
setTimeout(function() {
if (!self.isMounted()) { return; } // abandon
self.poll(); // do it once and then start it up ...
self._timer = setInterval(self.poll.bind(self), 15000);
}, 1000);
},
poll: function() {
var self = this;
$.get(self.props.source, function(result) {
if (self.isMounted()) {
self.setState({
error: false,
error_code: '',
error_message: '',
blogs: result.user.blogs,
user_id: result.user.id
});
}
}).fail(function(response) {
self.setState({
error: true,
error_code: response.status,
error_message: response.statusText
});
});
}

Categories

Resources