1

I'm using apollo to fetch data, how to achieve if the page re-rendered it will display the new data, how can I implement useQuery apollo in nextjs useEffect()?

import { GET_ALL_USERS } from "@/graphql/queries"
import { useQuery } from "@apollo/client"
import { useEffect } from "react";


export default function Home() {

  const { data, loading } = useQuery(GET_ALL_USERS);

  useEffect(() => {

  })


  return (
    <>
      <CreateUser />
      {
        loading ?
          <span>Loading data, Please wait...</span>
          :
          data?.getAllUsers.map((user: any, index: any) => {
            return <div key={index}>{user.name} {user.username}</div>
          })
      }
    </>
  )
}

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
erwin
  • 99
  • 2
  • 9

2 Answers2

1

It's a bad practice writing the useEffect without a dependency array. Also, why would the page re-render? Try to figure out why the page would re-render, and you'll get an idea of how to implement it. If it'd be of help, Apollo has a good document on Refetching Queries, so check that out as well.

But looking at the code, you should see the list of users, unless you have an error. Try pulling in the error aside from the loading and data and see if that's the reason why you're not seeing a list of the users.

Lazar Nikolov
  • 928
  • 14
  • 21
  • Hi Lazar the data is loading but when I insert new data it should show the new data automatically. refetch is taking too much resources on the server – erwin Mar 22 '23 at 02:54
1

Okay so since you want to display the new data after you insert it you'd need to edit the cache. This operation is free since it doesn't communicate with the server at all.

Depending on your situation, you'd either want to use writeQuery or cache.modify.

These two functions allow you to change the cached data locally without sending a request from the server. Using them in this situation would make total sense, since you're not worried about the validity and staleness of the data because you've just created the new data. You just want to display it without re-triggering the query.

Lazar Nikolov
  • 928
  • 14
  • 21