Call Api From React
Solution 1:
So after the long process of logging and debugging, I think I've figured out the issue.
Your initial state is creating the items property as an array and thus you're trying to map each item to an <li> to render to your UI, however the value you're getting back from your fetch call and reassigning this.state.items to isn't an array but a simple object. Therefore when you try to map the object, it fails, also explaining why your length condition is always failing.
Instead of directly reassigning items in the second .then handling of your fetch, replace it with this version of setState to maintain the array structure.
...
.then(newItem =>this.setState((prevState, props) => ({
items: [...prevState.items, newItem]
})
)
)
You may also want to push the fetch call back in the lifecycle of the component from the componentDidMount hook to the componentWillMount hook.
Post a Comment for "Call Api From React"