in React JS by
Q:

How to make AJAX call and in which component lifecycle methods should I make an AJAX call?

1 Answer

0 votes
by

You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.

For example, the employees list fetched from API and set local state:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      employees: [],
      error: null
    }
  }

  componentDidMount() {
    fetch('https://api. example. com /items')
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            employees: result.employees
          })
        },
        (error) => {
          this.setState({ error })
        }
      )
  }

  render() {
    const { error, employees } = this.state
    if (error) {
      return <div>Error: {error.message}</div>;
    } else {
      return (
        <ul>
          {employees.map(employee => (
            <li key={employee.name}>
              {employee.name}-{employee.experience}
            </li>
          ))}
        </ul>
      )
    }
  }
}
Click here to read more about React JS
Click here to read more about Insurance

Related questions

0 votes
0 votes
asked Jan 9, 2020 in Vue.JS by GeorgeBell
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Feb 24 in React JS by SakshiSharma
0 votes
asked Aug 19, 2019 in Selenium by rahulsharma
0 votes
asked Nov 25, 2019 in SOAPUI by rajeshsharma
...