jrich523 jrich523 - 7 months ago 15
Javascript Question

Javascript to update input is overwritten by placeholder

I have a simple input box with a placeholder value. There is a simple function that updates its value

socket.on('barcode', function (data) {
console.log('data received')
console.log(data);
var barcodeObj = document.getElementById("barcode")
barcodeObj.value = data;
})


I set a BP on this and the code actually inserts the barcode correctly just fine, however after checking that the function sets it correctly i continue running the app and then its quickly overwritten by the placeholder again.

This is running ReactJS and there is an onChange event, but, I would expect that to fire off correctly just fine.

the input is defined like this

<input
type="text"
id="barcode"
placeholder="barcode.."
value={this.state.barcode}
onChange={this.handleBarcodeChange}
/>


And the handler is setup like so

handleBarcodeChange: function(e) {
this.setState({barcode: e.target.value});
}


which, isnt doing anything crazy.

what am i missing here?

UPDATE:

I was able to get it working by injecting the following code in to my DeviceForm react class.

componentDidMount: function () {
var that = this;
this.socket = io();
this.socket.on('barcode', function (data) {
console.log('data received')
console.log(data);
that.setState({barcode: data});
});


This is from this code http://code.runnable.com/VOIYIALkqgAnHDmj/node-js-socket-io-and-react-js

Answer

I think you might just want to do something like this:

socket.on('barcode', function (data) {
    console.log('data received')
    console.log(data);
    this.setState({barcode: data});
}).bind(this)

setState should automatically update the DOM for you, meaning that this.state.barcode in your input will be automatically updated. Calling barcodeObj.value = data; will simultaneously trigger onChange, which might be causing your issue.

Comments