'Why ASYNC AWAIT doesnt work well in use effect in react
im trying to get user location, and then use the location to return relevant data for is location.
but in the second function i get that the location is null (when i console.log(location) it prints the right location, at the second print, the first print is null) it seems like the second function is not waiting until the first one is done.
Here is some code:
from the component
const location = useSelector(state => state.locationReducer.location);
useEffect(()=> {
(async () => {
await getLocation();
// here i'm using the location from the first function
await getInfo(location);
})()
}, []);
const getLocation = async() => {
try {
await dispatch(getLocation());
console.log(location);
} catch (err) {
// TODO HANDLE ERROR;
console.log('Err:', err);
}
}
in the action
export const getLocation = locationName => {
return async dispatch => {
try {
const location = **await** locationService.getLocation(locationName);
**await** dispatch(setLocation(location));
} catch (err) {
throw err;
};
};
};
const setLocation = location => {
return {
type: types.SET_LOCATION,
location
};
};
in service
async function getLocation(locationName) {
try {]
return **await** axios.get(`${url}/${locationName}`);
} catch (err) {
throw err
};
};
Solution 1:[1]
As Per Dan Abramov-
useEffect(() => {
async function fetchMyAPI() {
let url = 'http://something';
let config = {};
const response = await myFetch(url);
console.log(response);
}
fetchMyAPI();
}, []);
Here is the link for reference - https://github.com/facebook/react/issues/14326#issuecomment-441680293
Or You can simply use .then()
useEffect(() => {
asyncCall().then(setVal);
});
Article on how to fetch - https://www.robinwieruch.de/react-hooks-fetch-data
Solution 2:[2]
df<-data.frame(QID=c(1,2,3,4,5,6,7),
ABC_ABC=c(1,0,1,1,0,1,0),
DEF_DEF=c(0,1,0,0,0,0,0),
GHJ_GHJ=c(0,0,0,0,1,0,0),
None=c(0,0,0,0,0,0,1),
model=c(1,2,1,1,3,1,4))
nm <- names(df)[-c(1, 6)]
index <- apply(df[, -c(1, 6)], 1, which.max)
df$model_name <- nm[index]
df
#> QID ABC_ABC DEF_DEF GHJ_GHJ None model model_name
#> 1 1 1 0 0 0 1 ABC_ABC
#> 2 2 0 1 0 0 2 DEF_DEF
#> 3 3 1 0 0 0 1 ABC_ABC
#> 4 4 1 0 0 0 1 ABC_ABC
#> 5 5 0 0 1 0 3 GHJ_GHJ
#> 6 6 1 0 0 0 1 ABC_ABC
#> 7 7 0 0 0 1 4 None
Created on 2022-01-17 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AncientSwordRage |
| Solution 2 | Yuriy Saraykin |
