reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.71k stars 1.17k forks source link

RTKQuery - (0 , import_react2.useState) is not a function #1420

Closed afternoon2 closed 3 years ago

afternoon2 commented 3 years ago

Hello! I'm not sure if this is a RTK-Query related issue, but I've been digging the web for a solution for about 2 days now 😬

I've got a package inside a lerna-driven monorepo, which is an embedded React app. I'm using Redux toolkit for state management, and I wanted to use RTK-query for data fetching as well.

Everything works fine in the browser, but when it comes to testing, I'm getting following error on and on:

Error: Uncaught [TypeError: (0 , import_react2.useState) is not a function]

It is related to the @reduxjs/toolkit/dist/query/react/rtk-query-react.cjs.development.js:256:49 line in the bundle file:

var _g = (0, import_react2.useState)(), requestId = _g[0], setRequestId = _g[1];

I've got ^17.0.2 React and ReactDOM versions. Jest configuration looks as below:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  collectCoverageFrom: [
    'src/**/*.tsx',
    'src/**/*.ts',
    '!<rootDir>/node_modules/',
  ],
  coverageThreshold: {
    global: {
      branches: 90,
      functions: 90,
      lines: 90,
      statements: 90,
    },
  },
  coveragePathIgnorePatterns: ['index.ts', 'src/lib/testUtils'],
  moduleNameMapper: {
    '\\.scss$': 'identity-obj-proxy',
  },
  moduleDirectories: ['node_modules', '.'],
  roots: ['<rootDir>/src'],
  reporters: ['default', 'jest-sonar'],
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts']
};

The service looks as below:

export const service = createApi({
    reducerPath: 'service',
    baseQuery: fetchBaseQuery({
      baseUrl: API_URL,
    }),
    endpoints: (build) => ({
      loanProducts: build.query<
        LoanProductsResponsePayload,
        GetLoanProductParams
      >({
        query: (params: GetLoanProductParams) => ({
          url: 'loan-products',
          params,
        }),
      }),
      signup: build.mutation<SignupUserResponsePayload, SignupUserRequestBody>({
        query: (body) => ({
          url: 'signup',
          method: 'POST',
          body,
        }),
      }),
    }),
  });

export const { useLoanProductsQuery, useSignupMutation } = service;

And the failing test component inside the suite:

import { Provider } from 'react-redux';
import { render, screen } from '@testing-library/react';
import store from '..';
import { service } from './service';

test('signup endpoint hook', async () => {
    fetchMock.mockResponse(
      JSON.stringify(resPayload)
    );

    const Wrapper: React.FC = () => {
      const [load, { isError, error, isLoading, data }] = service.useSignupMutation();

      React.useEffect(() => {
        load(reqPayload);
      }, [load]);

      if (isError) {
        return <p>{error}</p>;
      }

      if (isLoading) {
        return <p>Loading</p>;
      }

      return (
        <>
          <p>{data?.email}</p>
        </>
      );
    };

   render(
      <Provider store={store}>
        <Wrapper />
      </Provider>
    );

    expect(await screen.findByText('linda.lovelace@example.com')).toBeDefined();
  });
phryneas commented 3 years ago

I'd assume that is somehow a problem with your bundler. Looking at that file, it contains

var import_react2 = __toModule(require("react"));

So that should definitely be there.

EduardValentin commented 2 years ago

Did you solve this? I have the same problem

yashar98 commented 2 years ago

i have same error. just add '/react' for importing from query. importing is different in react.

import { createApi } from '@reduxjs/toolkit/query' // don't use this

/* React-specific entry point that automatically generates
   hooks corresponding to the defined endpoints */
import { createApi } from '@reduxjs/toolkit/query/react' // use this one 
Rajikul340 commented 1 year ago

when i import getUsersQuery then the error is showing. how to solve this error

Unhandled Thrown Error! (0 , _feature_api_apiSliceWEBPACK_IMPORTED_MODULE_2__.useGetUsersQuery) is not a function TypeError: (0 , _feature_api_apiSliceWEBPACK_IMPORTED_MODULE_2__.useGetUsersQuery) is not a function at Home (http://localhost:3000/static/js/bundle.js:850:78) at renderWithHooks (http://localhost:3000/static/js/bundle.js:30230:22) at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:33516:17) at beginWork (http://localhost:3000/static/js/bundle.js:34812:20) at beginWork$1 (http://localhost:3000/static/js/bundle.js:39775:18) at performUnitOfWork (http://localhost:3000/static/js/bundle.js:39044:16) at workLoopSync (http://localhost:3000/static/js/bundle.js:38967:9) at renderRootSync (http://localhost:3000/static/js/bundle.js:38940:11) at recoverFromConcurrentError (http://localhost:3000/static/js/bundle.js:38432:24) at performConcurrentWorkOnRoot (http://localhost:3000/static/js/bundle.js:38344:26)