hi I was studying react and I've got something curious when I made this example. this code is that sending get request to newsapi, and receive the result. and I used custom hook for it.
// *** this is where I use custom hook. "usePromise" is custom hook. *** //
function NewsList({ category }) {
const [loading, response, error] = usePromise(() => {
console.log("how many will it run?")
const query = category === 'all' ? '' : `&category=${category}`;
return axios.get(
`https://newsapi.org/v2/top-headlines?country=kr${query}&apiKey=044c3c345f28417380cd3ea946ac8641`
);
},[category]);
console.log(loading);
...
I wrote console.log("how many will it run?") to check how many this function will run. and also console.log(loading) to check how many times loading will be changed
// *** this is custom hook's code *** //
export default function usePromise(promiseCreator, deps) {
const [loading, setLoading] = useState(true);
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const process = async () => {
await promiseCreator()
.then((res) => {
setResponse(res);
})
.catch((e) => {
console.log('catch');
setError(e);
});
setLoading(false);
};
process();
}, deps);
return [loading, response, error];
}
I wrote console.log('catch') to check how many this promise function will start. (Btw, cause of sending too many request, this code appears "error" when I send request)
// *** this is the console when I run this project on browser *** //
NewsList.jsx:31 true
NewsList.jsx:24 how many will it run?
NewsList.jsx:24 how many will it run?
usePromise.js:15 catch
NewsList.jsx:31 false
usePromise.js:15 catch
NewsList.jsx:31 false
as you can see. usePromise is excecuted twice. I knew loading will be consoled twice, "true" and "false" cause the function in usePromise is async. but I don't know why usePromise is executed twice. I expected it will be excecuted once when it is declared.
if you know the answer please comment for me. it would help me a lot thank you