2

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>
          );
        }
      }
}
asi hej
  • 143
  • 1
  • 10

1 Answers1

1

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>
    ))
}
GreenTeaCake
  • 848
  • 10
  • 17
  • That's because `result.items` is empty. Unfortunately I cannot tell you why. Please update your question according to https://stackoverflow.com/help/how-to-ask and https://stackoverflow.com/help/mcve – GreenTeaCake Jan 09 '19 at 17:10