reactjsreact-hooksfetchreact-query

Missing queryFn error when using useQuery


As the title suggests, I am new to using useQuery and the associated libraries, I am trying to use it to fetch data and then populates a list of fields that I have created However when I run it I get this error after it makes two requests

Missing queryFn index.js:1
    e index.js:1
    onError query.js:356
    reject retryer.js:67
    run retryer.js:132
    (Async: promise callback)
    run retryer.js:116
    Retryer retryer.js:156
    fetch query.js:330
    executeFetch queryObserver.js:199
    onSubscribe queryObserver.js:40
    subscribe subscribable.js:16
    useBaseQuery useBaseQuery.js:60
    React 5
    unstable_runWithPriority scheduler.development.js:468
    React 3
    workLoop scheduler.development.js:417
    flushWork scheduler.development.js:390
    performWorkUntilDeadline scheduler.development.js:157
    (Async: EventHandlerNonNull)
    js scheduler.development.js:180
    js scheduler.development.js:645
    Webpack 21

As far as I can tell I have passed in a query function so I am very confused why this error is showing I can see the server is receiving the requests and seemingly sends it, I have tested elsewhere and server does send it so it has to be with my code right?

const URL = 'http://localhost:3500/monster';
const fetchMonster = async (id) => {
    console.log(id);
    let res = await fetch(`${URL}/${id}`);
    if (!res.ok) {
        throw new Error('Network response was not ok');
    }
    return res.json;
};
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: process.env.NODE_ENV === 'production',
            refetchOnWindowFocus: false,
        },
    },
})

function EditMonster(props) {
    let { slug } = useParams();
    return (
        <QueryClientProvider client={queryClient}>
            <Query
                slug={slug} />
        </QueryClientProvider>
    )
}

function Query(props) {
    const { isLoading, error, data } = useQuery('monster', fetchMonster(props.slug))

    if (isLoading) return 'Loading...';
    if (error) return 'An error has occured: ' + error.message;

    return (
        <AttributeFields name='Edit Monster' method='PATCH' monster={data} />
    )
}

Solution

  • useQuery('monster', fetchMonster(props.slug))

    this code does not pass a function to useQuery - it immediately invokes the function. What you want is:

    useQuery('monster', () => fetchMonster(props.slug))

    As a side note, dependencies to the query function should go to the query key:

    useQuery(['monster', props.slug], () => fetchMonster(props.slug))