I'm trying to build a web page which listens for any keypresses and sends a POST request to a server to obtain some data. Using the data returned back, I wanted to render that onto the webpage.
Originally, to get keypresses, I had an HTML file and in the header, I had a script tag which looked something like this:
<script type="text/javascript">
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
console.log(charStr);
var params = {
key: charStr
};
var form = document.createElement("form");
console.log(form);
form.method = "post";
form.action = "http://localhost:8888/";
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.type = "hidden";
hiddenField.name = key;
hiddenField.value = params[key];
console.log(hiddenField);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
};
</script>
Now I'm using React as I want to listen for any keypresses and render the returned data onto the webpage without having to refresh. I have a component which looks something like this
class myComponent extends React.Component {
constructor() {
super();
this.state = {
x: null,
y: null,
z: null
};
}
componentDidMount() {
fetch("/some-endpoint")
.then(res => res.json())
.then(
returnData => this.setState(returnData),
() => console.log("State has been set to the return data")
);
}
render() {
return (
<div>
<h1>{this.state.x}</h1>
<h2>{this.state.y}</h2>
<h2>{this.state.z}</h2>
</div>
);
}
}
What I want to do is basically have that script that I was running in the HTML snippet above running somewhere in this component, but I'm unable to simply copy paste it into a script tag in my div and return it along with the HTML as I get errors saying stuff like "')' expected" and I'm really not sure what they mean in this context.
I feel like I may be approaching this the wrong way, but basically, I want to be able to add that functionality into my web page with React. I think it would have to be in the same component as myComponent to tell this component to update its state, but I could be wrong about that. If anyone can point me along the right path or give me some guidelines, that would be immensely helpful. Thanks in advance!
returnData => this.setState(returnData). I'm not sure what you want to do with the other function, but your syntax is busted.