I am starting my journey into learning more about React and I wanted to try a project that searches a music API database. I came across some code that I wanted to utilize but it's was written in a class component and as the field is shifting into functional components I was trying to convert the code into a class component. Would someone be able to help?
import React, { Component } from 'react' import axios from 'axios' import Suggestions from 'components/Suggestions' const { API_KEY } = process.env const API_URL = 'http://api.musicgraph.com/api/v2/artist/suggest' class Search extends Component { state = { query: '', results: [] } getInfo = () => { axios.get(`${API_URL}?api_key=${API_KEY}&prefix=${this.state.query}&limit=7`).then(({ data }) => { this.setState({ results: data.data }) }) } handleInputChange = () => { this.setState({ query: this.search.value }, () => { if (this.state.query && this.state.query.length > 1) { if (this.state.query.length % 2 === 0) { this.getInfo() } } else if (.this.state.query) { } }) } render() { return ( <form> <input placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange} /> <Suggestions results={this.state.results} /> </form> ) } } export default Search
Here is a conversion of your component in functional component. I commented where i made changes:
const { API_KEY } = process.env;
const API_URL = 'http://api.musicgraph.com/api/v2/artist/suggest';
// declared as functional compoennt
const Search = () => {
// State are used through Hooks now
const [state, setState] = useState({
query: '',
results: [],
});
const getInfo = () => {
axios
.get(`${API_URL}?api_key=${API_KEY}&prefix=${state.query}&limit=7`)
.then(({ data }) => {
setState((prevState) => ({
...prevState, // Don't erase your previous state (unless it's needed)
results: data.data,
}));
});
};
const handleInputChange = () => {
setState(
(prevState) => ({
...prevstate, // Same, don't lose your previous state
query: this.search.value, // search is missing in your sample
}),
() => {
// Remove 'this' everywhere, it's useless in functional component
if (state.query && state.query.length > 1) {
if (state.query.length % 2 === 0) {
getInfo();
}
} else if (!state.query) {
}
}
);
};
// No render anymore, only return
return (
<form>
<input
placeholder='Search for...'
ref={(input) => (this.search = input)} // No idea where 'search' comes from, provide infos if you need help for this, a variable is missing i guess
onChange={() => handleInputChange()} // Arrow function to handle the 'this' context
/>
<Suggestions results={state.results} />
</form>
);
};
export default Search;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.