Last active
January 31, 2019 20:52
-
-
Save ramsaylanier/42103d740cd8a14317bd821e46ec4189 to your computer and use it in GitHub Desktop.
Prefetch Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react" | |
import usePrefetchQuery from "./usePrefetchQuery.js" | |
import {SomeGraphQlQuery} from "./queries.gql" | |
import List from "./List" | |
const SomeComponent = props => { | |
const [prefetch, setPrefetch] = useState(false) | |
const { data, loading } = usePrefetchQuery({query: SomeGraphQlQuery})(prefetch) | |
return ( | |
<div onMouseEnter={() => setPrefetch(true)}> | |
{loading && <div>Loading...} | |
{data && <List items={data}/> | |
</div> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from "react" | |
import client from "@/graphql/client" | |
const usePrefetchQuery = ({ query, variables }) => prefetch => { | |
const [data, setData] = useState(null) | |
const [loading, setLoading] = useState(false) | |
const load = async () => { | |
const { data } = await client.query({ query, variables }) | |
setData(data) | |
setLoading(false) | |
} | |
useEffect( | |
() => { | |
setLoading(true) | |
prefetch && load() | |
}, | |
[prefetch] | |
) | |
return { data, loading } | |
} | |
export default usePrefetchQuery |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment