[英]How do I make a use effect run before another while using an API in react.js
The purpose of this project is to dynamically get the coordinates and bounds from a map API and use its values to get the data of places attached to that area这个项目的目的是从一个 map API 动态获取坐标和边界,并使用它的值来获取附属于该区域的地方的数据
The situation I have is that on my app.js I have two use effects:我的情况是在我的 app.js 上有两个使用效果:
the first is to get the user's location after the window is loaded this makes it possible for the map API to work.第一个是在加载 window 后获取用户的位置,这使得 map API 可以工作。
the second is to get the data from a different API based on the bounds gotten from the map.第二种是根据从 map 获得的边界从不同的 API 获得数据。
const App =() => { const [places, setPlaces]= useState([]); const App =() => { const [places, setPlaces]= useState([]); const [coordinates, setCoordinates] = useState({lat: 0, lng: 0});
const [坐标,setCoordinates] = useState({lat: 0, lng: 0}); const [bounds, setBounds]= useState(null);
const [bounds, setBounds]= useState(null);
useEffect(()=>{ let mounted = true; window.addEventListener('load', (event) => { navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => { if (mounted){ setCoordinates({ lat: latitude, lng: longitude }); } },(err)=> { console.warn(`ERROR(${err.code}): ${err.message}`); },{maximumAge:60000, timeout:5000, enableHighAccuracy:true}); console.log('page is fully loaded'); }); return ()=>{ mounted = false; } }, []); useEffect(() => { console.log(coordinates, bounds); let isApiSuscribed= true; getPlacesData(bounds.sw, bounds.ne)//I am trying to get the API data using this.then((data) => { if (isApiSuscribed){ console.log(data); setPlaces(data); } }); return ()=>{ isApiSuscribed=false; } }, [coordinates,bounds]); return( <> <CssBaseline /> <Header /> <Grid container spacing={3} style={{width:'100%'}}> <Grid item xs={12} md={4}> <List places={places}/> </Grid> <Grid item xs={12} md={8}> <Map setCoordinates={setCoordinates} setBounds = {setBounds} coordinates ={coordinates} /> </Grid> </Grid> </> ) } export default App;
The Challenge is that if I do not call the bounds.sw, bounds.ne
parameters in the getPlacesData()
function my Locally hosted page would run showing the appropriate Map and other components but the data that I need to fetch from the other API would not work.挑战在于,如果我不调用
getPlacesData()
function 中的bounds.sw, bounds.ne
参数,我的本地托管页面将运行并显示相应的 Map 和其他组件,但我需要从其他 API 获取的数据将不行。
And when I then call the bounds.sw, bounds.ne
parameters in the getPlacesData()
function then nothing is rendered on the screen and I get the following error codes: Error Message然后,当我在
getPlacesData()
function 中调用bounds.sw, bounds.ne
参数时,屏幕上没有任何内容呈现,我得到以下错误代码:错误消息
this is the code for the API that is to return the data back这是用于返回数据的 API 的代码
import axios from 'axios';
const URL ='https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary';
export const getPlacesData = async (sw, ne) => {
try {
const { data: { data } } = await axios.get(URL, {
params: {
bl_latitude: sw.lat,
bl_longitude: sw.lng,
tr_longitude: ne.lng,
tr_latitude: ne.lat,
},
headers: {
'x-rapidapi-key': process.env.REACT_APP_RAPID_API_TRAVEL_API_KEY,
'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',
},
});
return data;
} catch (error) {
console.log(error);
}
};
Please what do I do?请问我该怎么办?
It would be better if you could chain these operations instead of two disconnected useEffect
s.如果您可以链接这些操作而不是两个断开连接的
useEffect
会更好。 Try calling the getPlacesData
function where you're now changing the state using setCoordinates
, inside the first useEffect
.尝试在第一个 useEffect 中使用
setCoordinates
调用getPlacesData
function 来更改useEffect
。
I would also recommend extracting this out into a custom hook to make the code cleaner.我还建议将其提取到自定义挂钩中以使代码更清晰。
As a side note, you might not actually need window.addEventListener
since this component will already have mounted when the first useEffect is triggered.附带说明一下,您实际上可能不需要
window.addEventListener
,因为在触发第一个 useEffect 时该组件已经挂载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.