Your question is Refactor Class to Functional. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
Rooms To Go's storefront has a wishlist widget still written as a class component. It polls for updates and lets a shopper remove an item, but it's been flagged for occasional crashes when navigating away mid-poll.
import React from 'react';
class ProductWishlist extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
loading: true,
};
this.timer = null;
}
componentDidMount() {
this.fetchWishlist();
this.timer = setInterval(() => this.fetchWishlist(), 15000);
}
componentWillUnmount() {
// cleanup left incomplete
}
fetchWishlist() {
fetch('/api/wishlist/' + this.props.customerId)
.then(res => res.json())
.then(data => {
this.setState({ items: data, loading: false });
});
}
removeItem(sku) {
const items = this.state.items;
items.splice(items.findIndex(i => i.sku === sku), 1);
this.setState({ items: items });
}
render() {
if (this.state.loading) {
return <p>Loading wishlist...</p>;
}
return (
<ul>
{this.state.items.map(item => (
<li>
{item.name} - ${item.price}
<button onClick={() => this.removeItem(item.sku)}>Remove</button>
</li>
))}
</ul>
);
}
}
export default ProductWishlist;
Refactor this into a React 16.8+ functional component using hooks, and fix everything you find along the way — explain what you're fixing and why as you go.