0

I am new to React and TanStack and i try to write a React SPA (TypeScript) which shows up a data table after a successful login. The project uses TanStack Query V5, axios for data fetching and React Router for page handling. The backend expects a POST request (e.g. http://localhost:82/api/) with json formatted parameters. The json parameters have a header object with some common values for the api (e.g. current date/time, cookie, an incrementing command counter (counter is incremented every time a request is made), the command tag itself (e.g. "login", "GetData" ...) and a json parameter object. Now i tried to write a global useQuery hook which takes the command tag and the parameter object (defined as Interface), fills in the common stuff (date/time, increments command counter ...), sets the parameter interface object, posts the request and returns the answer from server.

i have

    const apiUrl = axios.create({ 
      baseURL: "http://localhost:82/api/", 
    });

    const queryClient = new QueryClient({
       defaultOptions: { 
         queries: { 
           queryFn: defaultQueryFn, 
         }, 
       }, 
     });

    const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => 
    {     
       const { data } = await apiUrl.post<IQueryRequest>("", {         
         method: queryKey[0],         
         cookie: "todo",         
         stamp: new Date().toISOString(),         
         ref_cmd: ++ref_cmd,         
         data: queryKey[1],     
       });     
       return data; 
    };
    
    export const useLogin = (username: string, password: string) => 
    {
      const param: IQueryParamLogin = {
        login: username,
        pwd: password,
      };
    
      // corrected this according to answer below
      return useQuery({
          queryKey: ["UserLogin", param],
          staleTime: Infinity,
      )};
            
    export default defaultQueryFn;

// i want to call it like this: const loginUser = async (username: string, password: string) => { useLogin(username, password) .then((res) => { if (res) { // process res } }) .catch((/e/) => toast.warning("Server error occured")); };

But i get error:

Property 'then' does not exist on type 'UseQueryResult<unknown, Error>'. Property 'then' does not exist on type 'QueryObserverRefetchErrorResult<unknown, Error>'.

0

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.