Guest User

Untitled

a guest
Jan 25th, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2.  
  3. class ItemList extends React.Component {
  4.  
  5.    // 1. Initialize `items` with an empty array
  6.    state = {
  7.        items: []
  8.    }
  9.  
  10.  
  11.  
  12.    // 2. Implement a componentDidMount which calls the fetchItems method
  13.    componentDidMount() {
  14.        this.fetchItems();
  15.    }
  16.  
  17.    componentDidUpdate(prevProps) {
  18.        if (this.props.newItem !== prevProps.newItem) {
  19.            const newItem = this.props.newItem;
  20.            // 3. Write a condition that check whether the state variable items has the newItem and also check
  21.            //    using a find function whether `this.state.items` has an item with same name
  22.            if (!this.state.items.includes(newItem) && !this.state.items.find(item => item.name === newItem.name)) {
  23.                this.fetchItems();
  24.            }
  25.        }
  26.    }
  27.  
  28.    fetchItems() {
  29.        fetch('/items')
  30.          .then(response => response.json())
  31.          .then(items => {
  32.            // 4. Set the state with the items
  33.            this.setState({
  34.              items: items
  35.            });
  36.          })
  37.          .catch(error => {
  38.            console.error(error);
  39.          });
  40.      }
  41.  
  42.    render() {
  43.        return (
  44.            <ul>
  45.            {this.state.items.map(item => (
  46.                // 5. Add the list item here
  47.              <li key={item.id}>{item.name}</li>
  48.            ))}
  49.          </ul>
  50.        );
  51.    }
  52. }
  53.  
  54. export default ItemList;
Advertisement
Add Comment
Please, Sign In to add comment