Migwell
Migwell

Reputation: 20107

How to obtain the `initialQueryRef` in Relay?

In the Relay docs, to fetch a query you have to first preload it using useQueryLoader, and then later pass the result of this into usePreloadedQuery. However, this first step, useQueryLoader takes two arguments: a query itself, which is easy to obtain, and preloadedQueryReference, which the docs do not explain how to obtain. All they say is " e.g. provided by router", but no router actually supports Relay with hooks so this is not helpful information.

As a simple example of this, I have a single component where I want to preload and then use a query:

import {
    usePaginationFragment,
    usePreloadedQuery,
    useQueryLoader
} from "react-relay";
import graphql from 'babel-plugin-relay/macro';

const MY_QUERY = graphql` some stuff here `;

export default function SomeComponent(props) {
    const initialRef = ???????;
    const [
        queryReference,
        loadQuery,
        disposeQuery,
    ] = useQueryLoader(AllHits, initialRef);

    const qry = usePreloadedQuery(AllHits, queryReference);
}

However without the initialRef, I can't proceed any further. How do I obtain this?

Upvotes: 4

Views: 1589

Answers (1)

Migwell
Migwell

Reputation: 20107

It seems that the query ref is returned from useQueryLoader or loadQuery. The argument to useQueryLoader (initialRef in the original post) is optional, and might be derived from a previous call to loadQuery done by the router, but it in no way required. An example of using useQueryLoader which loads the query as soon as possible is this:

const some_query = graphql` some query here`;

function Parent(props){
    // Note, didn't pass in the optional query ref here
    const [
        queryRef,
        loadQuery,
        disposeQuery
    ] = useQueryLoader(some_query); 

    // Load immediately
    useEffect(() => {
        loadQuery(
            {count: 20},
            {fetchPolicy: 'store-or-network'},
        );
    }, [loadQuery]);


    if (!!queryRef) {
        return <Child queryRef={queryRef}/>;
    } else {
        return "loading...";
    }
}

export function Child(props) {
    const {queryRef} = props;
    const loaded = usePreloadedQuery(some_query, queryRef);
    const { data } = useFragment(
        graphql`some_fragment`,
        loaded
    );
    return JSON.stringify(data);
}

Upvotes: 5

Related Questions