2

I am experiencing the below error when I introduce useQueryClient? Any ideas why this may be?

I am trying to invalidateQueries for a queryKey onSuccess of the useUpdateEmployee hook.

bundle.js:1427 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

Component

import { useFetchEmployee, useUpdateEmployee } from '../Users/Usershooks';

const User = () => {

    const userData = {
        name: 'test'
    };

    const { data } = useFetchEmployee(userID);
    const { mutate } = useUpdateEmployee(userID, userData);

    const saveChangesOnClick = () => {
        mutate();
    };

    return (
        <div>
            ...
        </div>
    );
};

export default User;

HookFile

import axios from 'axios';
import { useMutation, useQuery, useQueryClient } from 'react-query';

const queryClient = useQueryClient();

export const useFetchEmployers = () => useQuery(['fetchEmployers'], () => axios.get('https://jsonplaceholder.typicode.com/users')
    .then(response => response.data));

export const useFetchEmployee = (userID: any) => useQuery(['fetchEmployers', userID], () => axios.get(`https://jsonplaceholder.typicode.com/users/${userID}`)
    .then(response => response.data));

export const useUpdateEmployee = (userID: any, userData: any) => useMutation(
    () => axios.put(`https://jsonplaceholder.typicode.com/users/${userID}`, userData)
        .then(response => response.data),
    {
        onSuccess: () => {
            console.log("success");
            queryClient.invalidateQueries(['fetchEmployers']);
        }
    }
);

1 Answer 1

3

useQueryClient is a hook, it has to be initialized in a React component or in a custom hook. Just move it inside the useUpdateEmployee.

export const useUpdateEmployee = (userID: any, userData: any) => {
   const queryClient = useQueryClient();

   return useMutation(
      ...,
      onSuccess: () => {
        queryClient.invalidateQueries(['fetchEmployers']);
     }
   );
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.