useSWR modified returned data causing infinite loop inside useEffect #1233
Unanswered
RSchneider94
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I was able to fix it wrapping the SWR into a custom hook and seems to be working fine. Any thoughts/something that could get problem regarding SWR on the code? export function useUserPortfolios(userToken) {
const [portfolios, setPortfolios] = useState({
userPortfolios: {},
companyPortfolios: {},
});
const swrKey = userToken ? [portfoliosPath, userToken] : null;
const { data, error } = useSWR(swrKey, fetchUserPortfolios);
useEffect(() => {
if (data) {
const userPortfolios = {};
const companyPortfolios = {};
Object.entries(data).forEach(([key, value]) => {
if (Object.prototype.hasOwnProperty.call(value, 'organization')) {
companyPortfolios[key] = value;
} else {
userPortfolios[key] = value;
}
});
setPortfolios({ userPortfolios, companyPortfolios });
}
}, [data]);
return {
portfolios,
isLoading: !error && !portfolios,
isError: error,
mutate: () => mutate(swrKey),
};
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello community!
I'm using SWR for a while in a project and working pretty fine. However, today I've stumbled upon this problem. What I'm doing:
This is the function which I use to call the
useSWR
:which calls the following fetcher function:
And I'm calling it here (inside functional component):
and the
allPortfolios
I'm using inside auseEffect
function (which is also used as dependency of it):and here is where I'm currently having trouble. I don't know why exactly (this is the first time I have it with SWR) but it's getting updated/called again every time, and with that, causing
useEffect
to run again and again and you know, infinite loop, crash. But why? I have tried to remove it from dependency array in order to check and yes, it was the SWR. Also tried to give SWR some options in order to not fetch on focus, etc. but even though is breaking my app.Any ideas?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions