Search code examples
javascriptreactjsundefinedfetchsetstate

After fetch state returns undefined


Im using fetch to post data to my local api, but when trying to get them and error like this occures. In fetch i get result perfectly fine, but after that trying to pass that into state like below:

this.setState({ items: result.items })

but items returns undefined and don't know why ?

My code:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
          items: [],
          error: null,
          isLoaded: false

        };
        this.setState = this.setState.bind(this);
      }

      componentDidMount() {
        fetch("http://localhost:3000/items")
          .then(res => res.json())
          .then(result => {   
                console.log(result);
              this.setState({
                items: result.items,
                isLoaded: true
              });
                console.log(this.state.items)
            },                       
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }


      render() {
        const { error, isLoaded, items } = this.state;
        if (error) {
          return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
          return (

            <ul>
                <h1>Saved items:</h1>
              {
                items && items.map(item => (
                    <li key={item.name}>
                       item: {item.name} {item.price}
                    </li>
                ))
            }
            </ul>
          );
        }
      }
}

Solution

  • You can do either:

    this.setState({
        items: result.items || [],
         isLoaded: true
    });
    

    or

    {
        items && items.map(item => (
            <li key={item.name}>
                {item.name} {item.price}
            </li>
        ))
    }