'How to add catch error to my axios API code

THE CODE BELOW DISPLAYS POST FROM REDDIT, how can i make it display error if http is incorrect? if the data is not gotten.

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import axios from 'axios'

class Reddit extends React.Component {
  state = {
    posts: [],
  }
  componentDidMount() {
    axios
      .get(`https://www.reddit.com/r/${this.props.subreddit}.json`)
      .then((res) => {
        const posts = res.data.data.children.map((obj) => obj.data)
        this.setState({ posts })
      })
  }
  render() {
    const { posts } = this.state
    return (
      <div>
        <h1>{`/r/${this.props.subreddit}`}</h1>
        <ul>
          {posts.map((post) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      </div>
    )
  }`
}

ReactDOM.render(<Reddit subreddit='reactjs' />, document.querySelector('#root'));

THE CODE BELOW DISPLAYS POST FROM REDDIT, how can i make it display error if http is incorrect? if the data is not gotten.



Solution 1:[1]

You can use .catch() method

axios
    .get(`https://www.reddit.com/r/${this.props.subreddit}.json`)
    .then((res) => {
        const posts = res.data.data.children.map((obj) => obj.data)
        this.setState({
            posts
        })
    })
    .catch((error) => {
        console.log('something went wrong')
    })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 norbekoff