简体   繁体   中英

React/Redux: how to call an API after getting data from the browser?

My React app is supposed to display nearby shops to each user depending on their location.

What I'm trying to do is to get the latitude/longitude by window.geolocation in the componentDidMount() in which I'll call a REST API with the latitude/longitude as params to retrieve nearby shops.

I'm just trying to figure out how to organize and where to put the logic.

The idea is that you should try to use React's state before reaching for redux. It's both simpler and keeps as much of the state local as possible.

The React state stores the status of the API call (not made yet, success or failure) and the corresponding information about success ( results ) or failure ( errorMessage ). The important point is that your render function must explicitly handle all 3 cases.

 class NearbyShops extends React.Component { constructor(props) { super(props); this.state = { queryStatus: 'initial', results: [], errorMessage: '', } } async componentDidMount() { try { const results = await fetch('you.api.url/here'); this.setState(prevState => ({...prevState, results, queryStatus: 'success'})) } catch (e) { this.setState(prevState => ({...prevState, queryStatus: 'failure', errorMessage: e})) } } render() { const {results, queryStatus, errorMessage} = this.state; if (queryStatus === 'success') { return ( <div>{/* render results here */}</div> ) } else if (queryStatus === 'failure') { return ( <div>{errorMessage}</div> ) } else { return ( <div>Loading nearby shops...</div> ) } } } 

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