Next.js Discord

Discord Forum

api call every time route changes

Answered
Rex posted this in #help-forum
Open in Discord
RexOP
Alright I have a home page where I am fetching profiles and displaying them. I have an about page as well. Whenever I change the route and come back to the "home" route request is made to the db to get the profile. I believe that's not a good thing.
it should have some sort of caching
Here is how I am making api request
"use client"
const InfiniteScrollComponent = ({ userProfile }: any) => {
  const supabase = createClient();

  const [data, setData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(2);

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

  const fetchData = async () => {
    try {
      if (userProfile) {
        const { data: newData, error: someError } = await supabase
          .rpc("get_profiles_near_user_new", {
            user_location: `SRID=4326;POINT(${userProfile[0].location.coordinates[0]} ${userProfile[0].location.coordinates[1]})`,
            max_distance: 100000,
          })
          .range(page * perPage - perPage, page * perPage - 1);

        if (someError) throw someError;

        if (newData.length < perPage) {
          setHasMore(false); // No more data available
        }
        // @ts-ignore
        setData([...data, ...newData]); // Append new data to existing data
        setPage(page + 1);
      }
    } catch (error) {
      // @ts-ignore
      console.error("Error fetching data:", error.message);
    }
 }
return (
// infinite scroll comp here
)

what can i do?
Answered by Jboncz
Then cache it on the backend of your nextjs app, and fetch from client side to server side, server side can cache the data from the db.
View full answer

42 Replies

RexOP
the api returns 10 profiles (or posts samething) and displays on the home feed. Should not I somehow cache that?
maybe I should not
now that I have typed it out it sounds not so good
I dont have a confident answer for you :/ I just think cacheing photos is a bad idea, photos are large typically.
RexOP
not sure
what if there is some text
similar to twitter feed
what then
I wouldnt cache that on the users computer either 🤷‍♂️
What if it was edited?
RexOP
yeah you are right
ok one more questiion
using react query with supabase does that makes sense
for any valid secanrio or does these two thing not go with each other
The two arent related, one is a db and one is a fetching framework. I use raw fetch calls, but react-query has benefits that are abstracted away from the user, which is good most of the time. There isnt a wrong or right answer, if you like react-query use it.
RexOP
for now I am doing data fecthing using supabase
but lets see
Your using react-query to fetch from your front end to your backend though right?
RexOP
I am just using supabase directly to fetch data from db. not through api routes.
Oh your fetching from the db client side?
RexOP
supabase provides both client side and server side
Ive never used supabase, so im not familiar
RexOP
yes
Nice, then what is your use case for react-query?
RexOP
I am also using for the first time so don;t know if doing it the right way or not
unfortunately I dont have an answer for your question :/
RexOP
I don't wanna hit db every time pages loads for certain routes
@Jboncz unfortunately I dont have an answer for your question :/
RexOP
you still trying to help means a lot
Then cache it on the backend of your nextjs app, and fetch from client side to server side, server side can cache the data from the db.
Answer
so not directly fetched from supabase, but from your backend
RexOP
this is new info for me
I will look into this
np 🙂 I cant tell you its the right way to do it, I personally wouldnt want to cache images, but I also self host all of my stuff through work and its an internal application so there is no bandwidth or fetching limitations.
everything is self hosted, instead of using vercel or some vps
You will likely want to do what ever is most cost efficient.
RexOP
umm
if fetching from the db is 50% the price of fetching from vercels backend then rather fetch from the db
RexOP
will have to figure out the optimal way
Make sure you mark the answer before you go so it closes the thread 🙂
RexOP
Sorry I forget because only this server has mark solution feature