Axios cannot allow state element to react
I am brand new to react and follow the guide. The instructor uses axioms to pull some data from the github api. Below is what it offers as a handler for the onSubmit event:
handleSubmit = (event) => {
event.preventDefault();
console.log('event: form submit ' + this.state.userName )
axios.get('https://api.github.com/users/${this.state.userName}')
.then(resp => {
console.log(resp)
});
}
However, when I run it, this.state.userName
it is not resolved and I get a 404. Is there something wrong with the code or axioms? I am using jscomplete / repl playground to work with it.
Help rate!
Below is the component code:
class Form extends React.Component {
state = {
userName: ' ',
event: ' '
}
handleSubmit = (event) => {
event.preventDefault();
console.log('event: form submit ' + this.state.userName )
axios.get('https://api.github.com/users/${this.state.userName}')
.then(resp => {
this.setState({event: resp})
});
console.log(event)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.userName}
onChange={(event) => this.setState({userName: event.target.value})}
placeholder={ this.state.username } required
/>
<button>Add Card</button>
</form>
)
}
}
source to share
you are not using ES6 template literals as you should.
on that line, you have wrapped the line in '
:'https://api.github.com/users/${this.state.userName}'
wrap it with back check marks (') (with a tilde button)
source to share
You should really use a constructor to initialize state variables. Use backtick ( ` ) to replace variables in a string. Also bind the function to the class using context this
. Try the following code
class Form extends React.Component {
constructor(props) {
super(props)
this.state = {
userName: ' ',
event: ' '
}
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit = (event) => {
event.preventDefault();
console.log('event: form submit ' + this.state.userName)
axios.get(`https://api.github.com/users/${this.state.userName}`)
.then(resp => {
this.setState({ event: resp })
});
console.log(event)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.userName}
onChange={(event) => this.setState({ userName: event.target.value })}
placeholder={this.state.username} required
/>
<button>Add Card</button>
</form>
)
}
}
source to share