Home > Enterprise >  How to change this class component into a function component?
How to change this class component into a function component?

Time:07-30

I have this class component that extracting data from a JSON API. I would like to know how to convert into a function component rather than a class component.

class Blah extends React.Component{
  constructor(){
    super();
    this.state = {results:[]};
  }
  componentDidMount(){
    var url = "https://api.spoonacular.com/recipes/complexSearch?&apiKey=5ee5ea02063941f49492c145e967b7a8";
    fetch(url)
      .then((x) => x.json())
      .then((json) => this.setState({results:json.results}));

  }
  render(){
    return <div>
      {this.state.results.map(lol => <ShowDietPage food={lol.title}/>)}
    </div>
  }

}

CodePudding user response:

You can replace componentDidMount with useEffect hook and this.state = {results:[]} with useState hook. Should look something like this:

const BlahFunctionalComponent = () => {
  const [results, setResults] = useState([]);

  useEffect(() => {
    var url =
      "https://api.spoonacular.com/recipes/complexSearch?&apiKey=5ee5ea02063941f49492c145e967b7a8";
    fetch(url)
      .then((x) => x.json())
      .then((json) => setResults(json.results));
  }, []);

  return (
    <div>
      {results.map((lol) => {
        <ShowDietPage food={lol.title} />;
      })}
    </div>
  );
};
  • Related