import { View } from "react-native";
import React, { useState, useEffect } from "react";
import Memory from "../component/Memory";
import sanityclient from "../memories-20/sanityclient";
const Memories = () => {
const [memories, setMemories] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [startIndex, setStartIndex] = useState(0);
const batchOfMemories = memories.slice(startIndex, startIndex + 3);
const fetchData = () => {
sanityclient
.fetch(
`*[_type == "memory"] | order(date desc) {
...,
}`
)
.then((data) => {
setMemories(data);
console.log(memories);
setIsLoading(false);
});
};
useEffect(() => {
fetchData();
}),
[];
return (
<View className="flex-1 items-center bg-transparent justify-center">
<View>
<View className="flex items-center w-full h-[90%]">
{!isLoading ? (
<View>
{batchOfMemories.map(
(memory, index) =>
<Memory />
)}
</View>
) : (
<Loading />
)}
</View>
</View>
</View>
);
};
export default Memories;
I'm using React Native - Expo with Sanity.io
The problem is that the fetchData function runs infinitely which is making the API Request count massive.
How do I make it so that it only runs on page load? or if possible, runs only if there is change?
I solved it simply just by adding a if check before running the fetch
Not the best solution, the function still runs infinitely but atleast the API doesn't get called because the variable already has data in it