Abdullah Mohammed
Abdullah Mohammed

Reputation: 3

Convert a class component into a function component

I want to convert this class component into a function component. I tried a lot and failed. Is there a solution to the problem?

componentDidMount(){
    const id = this.props.match.params.id;
    getById( parseInt(id) )
    .then(product => {
    this.setState({
      product,
      loading: false
    });
  })
}

Upvotes: 0

Views: 99

Answers (1)

tmhao2005
tmhao2005

Reputation: 17524

The following snippet is equal componentDidMount in class component:

// ...
const [loading, setLoading] = React.useState(false);
const [product, setProduct] = React.useState(void 0);

React.useEffect(() => {
  // Did mount, put your code here
  setLoading(true)
 
  // Fetch done
  .then(product => {
    setLoading(false)
    setProduct(product)
  })

}, []);

Upvotes: 1

Related Questions