Attempting to make a call to an API to get some data and store it in my components state. I am using useEffect
with a []
dependency to fire only once. The setEntries
line causes Expo to panic and crash on iOS. If I comment that out, I can log and see that the API is returning what I would expect. I am wondering if some kind of infinite loop is being kicked off by calling setEntries
but I do not see that happening when I log to the console.
I have also tested adding isLoading
, entries
and isError
to the dependency array to no avail.
Relevant code below:
import React, { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, Text } from 'react-native';
import { globalStyles } from '../../../styles';
import Card from '../../shared/components/card';
import { Entry } from '../../shared/models/Entry';
import { REQUEST } from '../../shared/services/networking';
export const EntryList = () => {
const [entries, setEntries] = useState([]);
const [isError, setIsError] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((result) => {
setIsLoading(false);
if (result.ok) {
return result.json();
} else {
throw new Error(result.status.toString());
}
})
.then((entries) => {
if (entries) {
setEntries(entries.data.sort((a: Entry, b: Entry) => Date.parse(b.createdAt) - Date.parse(a.createdAt)));
}
})
.catch((e) => {
console.error(e);
setIsError(e);
});
}, []);
return (
<SafeAreaView style={globalStyles.container}>
<ScrollView showsVerticalScrollIndicator={false}>
{isError && <Text>Sorry, we encountered an error.</Text>}
{isLoading && <Text>Loading...</Text>}
{entries && !isLoading ? (
entries.map((entry, i) => <Card entry={entry} key={`entry-${i}`} />)
) : (
<Text>No entries found. Tell us about your day :)</Text>
)}
</ScrollView>
</SafeAreaView>
);
};
EDIT: Some additional detail that is further complicating this issue. When I run this code on my MacBook, Expo works properly. When I run the same code on my Linux desktop (Elementary OS), I get the behavior described above. Because of this, I have opened an issue with Expo here: https://github.com/expo/expo/issues/11352
I think issue might be because you have same name entries
in your state
and request response in .then((entries) => {...})
. Try to change name in your response like response or something like
.then((response) => {
if (response) {
setEntries(response.data.sort((a: Entry, b: Entry) => Date.parse(b.createdAt) - Date.parse(a.createdAt)));
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.