简体   繁体   中英

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.

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')
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM