Reputation: 645
I have a problem making the request and showing the results in the component. It's showing a performance error. I've tried some solutions that I found here on stackoverflow but none of them resolved. What exactly is this error and how can I fix it? More details about the error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
export function SelecionarEmpresa({ closeModalSelectCompany }: Props) {
const { token } = useAuth();
const { navigate } = useNavigation();
const [loading, setLoading] = useState(true);
const [empresas, setEmpresas] = useState([]);
useEffect(() => {
getAllEnterprises(token!, '7795297')
.then((res: any) => {
setEmpresas(res);
})
.catch((error: any) => {
alert("Erro ao buscar empresas" + error);
})
.finally(() => {
setLoading(false);
});
}, []);
return (
<S.Container>
<S.Gradient colors={['#8F012A', '#E67521']}>
<S.Image source={require('../../images/fundobnb.png')} />
<S.SafeArea>
{
loading && (
<S.ContainerLoading>
<ActivityIndicator size="small" color="#FFF" />
<S.Description>Carregando empresas...</S.Description>
</S.ContainerLoading>
)
}
{!loading && !empresas?.length && (
<S.Content>
<S.SubContent>
<CustomIcon name="ops" size={normalize(40)} color="#FFA439" />
<S.TitleError>Ops!</S.TitleError>
</S.SubContent>
<S.TextError>Você não está associado{'\n'} a nenhuma empresa.</S.TextError>
<ButtonCompany title="Continuar sem identificação" onPress={() => navigate('Home')} />
</S.Content>
)}
{!loading && empresas && empresas?.length > 0 && (
<S.Content>
<S.Title>Escolha</S.Title>
<S.Description>Deseja se conectar com qual empresa?</S.Description>
{
empresas.length > 0 && empresas?.map((item, index) => (
<ButtonCompany key={index} title={item.razaoSocial} onPress={() => alert('ok')} />
))
}
</S.Content>
)}
<S.Button onPress={null}>
<S.TextButton>Central de Atendimento</S.TextButton>
</S.Button>
</S.SafeArea>
</S.Gradient>
</S.Container>
)
}
Upvotes: 0
Views: 54
Reputation: 981
As far as I can see you are trying to execute an asynchronous task in your useEffect and update the state in case of success. After initiation the promise is added to the callstack and if the component is unmounted before the promise resolves/rejects it tries to update the state on an unmounted component. The solution would be to cancel your request in case of a component unmount - i.e. fire a cancellation function in a return statement of your useEffect. If you use Axios, check this guide for cancellation. If not - you can refer to this one.
Upvotes: 1