Sanity.io fetch function running infinitely

49 views Asked by At
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?

2

There are 2 answers

1
Putra Amir On

I solved it simply just by adding a if check before running the fetch

const fetchData = () => {
  if (!memories.length) {
    sanityclient
      .fetch(`*[_type == "memory"] | order(date desc) { ..., }`)
      .then((data) => {
        setMemories(data);
        setIsLoading(false);
      });
    console.log("fetch");
  } else {
    setIsLoading(false);
  }
};

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

0
DinhNguyen On

the fetchData function runs infinitely because you write wrong useEffect:

useEffect(() => {
  fetchData();
}),
  [];

Correct code:

useEffect(() => {
  fetchData();
}, []);