You can use any AJAX library you like with React. Some popular ones areAxios,jQuery AJAX, and the browser built-inwindow.fetch.
You should populate data with AJAX calls in thecomponentDidMount lifecycle method. This is so you can usesetState to update your component when the data is retrieved.
The component below demonstrates how to make an AJAX call incomponentDidMount to populate local component state.
The example API returns a JSON object like this:
{ "items": [ { "id": 1, "name": "Apples", "price": "$2" }, { "id": 2, "name": "Peaches", "price": "$5" } ] }classMyComponentextendsReact.Component{constructor(props){super(props);this.state={error:null,isLoaded:false,items:[]};}componentDidMount(){fetch("https://api.example.com/items").then(res=> res.json()).then((result)=>{this.setState({isLoaded:true,items: result.items});},// Note: it's important to handle errors here// instead of a catch() block so that we don't swallow// exceptions from actual bugs in components.(error)=>{this.setState({isLoaded:true, error});})}render(){const{ error, isLoaded, items}=this.state;if(error){return<div>Error:{error.message}</div>;}elseif(!isLoaded){return<div>Loading...</div>;}else{return(<ul>{items.map(item=>(<likey={item.id}>{item.name}{item.price}</li>))}</ul>);}}}Here is the equivalent withHooks:
functionMyComponent(){const[error, setError]=useState(null);const[isLoaded, setIsLoaded]=useState(false);const[items, setItems]=useState([]);// Note: the empty deps array [] means// this useEffect will run once// similar to componentDidMount()useEffect(()=>{fetch("https://api.example.com/items").then(res=> res.json()).then((result)=>{setIsLoaded(true);setItems(result);},// Note: it's important to handle errors here// instead of a catch() block so that we don't swallow// exceptions from actual bugs in components.(error)=>{setIsLoaded(true);setError(error);})},[])if(error){return<div>Error:{error.message}</div>;}elseif(!isLoaded){return<div>Loading...</div>;}else{return(<ul>{items.map(item=>(<likey={item.id}>{item.name}{item.price}</li>))}</ul>);}}