question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do you "Start Fetching Early"?

See original GitHub issue

If data fetching is happening in a selector, how would you kick off the request early - like in this example from the Suspense docs.

// First fetch: as soon as possible
const initialResource = fetchProfileData(0);

function App() {
  const [resource, setResource] = useState(initialResource);
  return (
    <>
      <button onClick={() => {
        const nextUserId = getNextId(resource.userId);
        // Next fetch: when the user clicks
        setResource(fetchProfileData(nextUserId));
      }}>
        Next
      </button>
      <ProfilePage resource={resource} />
    </>
  );
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
drarmstrcommented, Jun 11, 2020

The Suspense docs provide this example:

// Start fetching early!
const resource = fetchProfileData();

// ...

function ProfileDetails() {
  // Try to read user info
  const user = resource.user.read();
  return <h1>{user.name}</h1>;
}

Selectors follow a similar convention as components for Suspense. I haven’t tried this example with an outside source like this yet, but it should work. Let me know!

const resource = fetchProfileData();

const userNameQuery = selector({
  key: 'UserNameQuery',
  get: () = {
    const user = resource.user.read();
    return user.name;
  },
});

Or, you can just await on a pending pre-fetched promise:

const userPromise = fetchUser();

const userNameQuery = selector({
  key: 'UserNameQuery',
  get: async () = {
    const user = await userPromise;
    return user.name;
  },
});

You can use selectorFamily() to parameterize the selector. But, note that promises and functions don’t work well in parameters, so you’d want to use an id or handle to reference it.

If you want to do everything with just selectors, you can do that also by using useRecoilValueLoadable() because it does not block the rendering while the query is still loading.

const userNameQuery = selector({
  key: 'UserNameQuery',
  get: async () => {
    const user = await fetchUser();
    return user.name;
  },
});

function ProfilePage() {
  useRecoilValueLoadable(userNameQuery);  // initiate pre-fetch

  // Stat rendering while fetch was started
  return (
    <Suspense>
      <ProfileDetails />
    </Suspense>
  );
}

function ProfileDetails() {
  const userName = useRecoilValue(userNameQuery);
  return <h1>{userName}</h1>;
} 
0reactions
morgs32commented, Jun 11, 2020

Nice! So something like this? Seems pretty slick.


// userQuery.js
import getUser from 'getUser'
const userQuery = selectorFamily({
  key: 'UserNameQuery',
  get: async (userId) = {
    const user = await getUser(userId);
    return user;
  },
});

// App.js
import userQuery from './userQuery'
function App() {

  const earlyGetUser = useRecoilCallback(async ({getLoadable}, userId) => {
     getLoadable(userQuery(userId))
  });

  return (
    <UserPicture 
        onClick={(userId) => {
           earlyGetUser(userId)
           goToRoute('profile', { userId })
        }}
     />
  );
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Teach Your Dog to Fetch in 5 Steps - 2022 - MasterClass
Begin by teaching your dog the last step of the fetch process first—a training technique called "backchaining." First, wave your dog's ...
Read more >
How can I teach my retriever puppy to fetch? - Otter Tail Kennels
Start by taking your well-rested puppy to the fetching location you have chosen. · Knee down with the puppy at the open side...
Read more >
How to Teach Your Dog to Fetch - American Kennel Club
Teaching Fetch​​ Hold the toy out to your dog in your outstretched palm and ask her to “hold.” if your dog takes the...
Read more >
How to Teach a Dog to Fetch: A Step-by-Step Guide - BeChewy
Step 1: Start in Enclosed, Small Space. Stay in an enclosed spaced—like a hallway, fenced backyard or bedroom—during the early days of teaching ......
Read more >
6 Steps To Teaching Your Dog To Fetch - Cesar's Way
Start with Chasing ... If your dog is of the “sit and stare” variety, your first goal is to teach him to chase...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found