Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- class ItemList extends React.Component {
- // 1. Initialize `items` with an empty array
- state = {
- items: []
- }
- // 2. Implement a componentDidMount which calls the fetchItems method
- componentDidMount() {
- this.fetchItems();
- }
- componentDidUpdate(prevProps) {
- if (this.props.newItem !== prevProps.newItem) {
- const newItem = this.props.newItem;
- // 3. Write a condition that check whether the state variable items has the newItem and also check
- // using a find function whether `this.state.items` has an item with same name
- if (!this.state.items.includes(newItem) && !this.state.items.find(item => item.name === newItem.name)) {
- this.fetchItems();
- }
- }
- }
- fetchItems() {
- fetch('/items')
- .then(response => response.json())
- .then(items => {
- // 4. Set the state with the items
- this.setState({
- items: items
- });
- })
- .catch(error => {
- console.error(error);
- });
- }
- render() {
- return (
- <ul>
- {this.state.items.map(item => (
- // 5. Add the list item here
- <li key={item.id}>{item.name}</li>
- ))}
- </ul>
- );
- }
- }
- export default ItemList;
Advertisement
Add Comment
Please, Sign In to add comment