I would like to call an async function and get the result for my UseEffect.
The fetch api examples I found on the internet are directly made in the useEffect function. If my URL changes, I must patch all my fetchs.
When I tried, I got an error message.
This is my code.
async function getData(userId) {
const data = await axios.get(`http://url/api/data/${userId}`)
.then(promise => {
return promise.data;
})
.catch(e => {
console.error(e);
})
return data;
}
function blabla() {
const [data, setData] = useState(null);
useEffect(async () => {
setData(getData(1))
}, []);
return (
<div>
this is the {data["name"]}
</div>
);
}
index.js:1375 Warning: An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
awaitor.then(...), not both..thenreturns a promise, which can be awaited like any other. You don't have to, but it can arguably lead to cleaner code, like if you want to map the raw result of an API call into a more convenient object before returning it. Working example (see code in home.component.ts): codesandbox.io/p/devbox/boilerplate-forked-3dm6v6