Estoy trabajando en la creación de un espacio de yarn workspace para compartir código entre React y React Native (¡próxima publicación de blog una vez que esté completamente terminado!).
La parte más importante para nosotros es compartir la lógica comercial entre ambas plataformas. En este caso, estamos usando react-query para solicitudes de red.
Hemos creado un componente "Render prop" para eso
import { useAllDevices } from "../../queries/devices"; export interface DeviceListProps { devices: any[]; isLoading: boolean, onItemClick?: () => void; } export interface DeviceItemListProps { name: string; onItemClick?: () => void; } export const DeviceListContainer = ({ render }: { render: any }) => { const { data, isLoading } = useAllDevices(); return ( <> {render({ devices: data?.devices, isLoading })} </> ) } donde useAllDevices es algo como esto:
export const useAllDevices = () => useQuery('useAllDevices', async () => { const devicesResponse = await get('/todos'); return { devices: devicesResponse.data, }; });En la web, funciona de maravilla, pero recibo un error para la aplicación móvil. Parece que el problema es con react-query en sí mismo porque una vez que puse esto:
const queryClient = new QueryClient(); const App = () => { const isDarkMode = false; const backgroundStyle = { backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, }; return ( <QueryClientProvider client={queryClient}> <ThemeProvider theme={THEME}> <SafeAreaView style={backgroundStyle}> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} /> <ScrollView contentInsetAdjustmentBehavior="automatic" style={backgroundStyle}> <Header /> <Button styleType="primary">hey</Button> </ScrollView> </SafeAreaView> </ThemeProvider> </QueryClientProvider> ); };me sale este error
Funciona correctamente y sin problemas para la versión web de React.
mi package.json en el módulo de la aplicación es este
{ "name": "@sharecode/app", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest --updateSnapshot", "lint": "eslint . --ext .js,.jsx,.ts,.tsx" }, "dependencies": { "react": "17.0.2", "react-native": "0.67.3", "react-native-gesture-handler": "^2.3.0", "styled-components": "^5.3.3" }, "devDependencies": { "@babel/core": "^7.12.9", "@babel/runtime": "^7.12.5", "@react-native-community/eslint-config": "^2.0.0", "@sharecode/common": "1.0.0", "@testing-library/jest-native": "^4.0.4", "@testing-library/react-native": "^9.0.0", "@types/jest": "^27.4.1", "@types/react-native": "^0.66.15", "@types/react-test-renderer": "^17.0.1", "@types/styled-components-react-native": "^5.1.3", "@typescript-eslint/eslint-plugin": "^5.7.0", "@typescript-eslint/parser": "^5.7.0", "babel-jest": "^26.6.3", "eslint": "^7.14.0", "get-yarn-workspaces": "^1.0.2", "jest": "^26.6.3", "metro-config": "^0.56.0", "metro-react-native-babel-preset": "^0.66.2", "nock": "^13.2.4", "react-test-renderer": "17.0.2", "ts-jest": "^27.1.3", "typescript": "^4.4.4" }, "workspaces": { "nohoist": [ "react-native", "react-native/**", "react", "react/**", "react-query", "react-query/**" ] }, "resolutions": { "@types/react": "^17" }, "jest": { "preset": "react-native", "setupFilesAfterEnv": [ "@testing-library/jest-native/extend-expect" ], "moduleFileExtensions": [ "ts", "tsx", "js", "jsx", "json", "node" ] } }Paquete principal
{ "name": "@sharecode/common", "version": "1.0.0", "main": "index.ts", "license": "MIT", "dependencies": { "axios": "^0.26.0", "react-query": "^3.34.16", "styled-components": "^5.3.3" }, "devDependencies": { "@types/styled-components": "^5.1.24" } }Y paquete web (funcionando perfectamente)
{ "name": "@sharecode/web", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.2", "@testing-library/react": "^12.1.3", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.4.1", "@types/node": "^16.11.26", "@types/react": "^17.0.39", "@types/react-dom": "^17.0.13", "react": "17.0.2", "react-dom": "^17.0.2", "react-scripts": "^5.0.0", "typescript": "^4.6.2", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "eslint-config-react-app": "^7.0.0", "react-app-rewired": "^2.2.1" } }El error parece ser bastante sencillo, pero no puedo ver lo que está pasando
ERROR 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: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. This error is located at: in QueryClientProvider (at App.tsx:31) in App (at renderApplication.js:50) in RCTView (at View.js:32) in View (at AppContainer.js:92) in RCTView (at View.js:32) in View (at AppContainer.js:119) in AppContainer (at renderApplication.js:43) in NuoDoor(RootComponent) (at renderApplication.js:60) ✨ Done in 318.43s.Además, aquí está el resultado de `yarn why react``
javiermanzano@Javiers-MBP app % yarn why react yarn why v1.22.17 [1/4] 🤔 Why do we have the module "react"...? [2/4] 🚚 Initialising dependency graph... [3/4] 🔍 Finding dependency... [4/4] 🚡 Calculating file sizes... => Found "@sharecode/app#react@17.0.2" info Reasons this module exists - "_project_#@sharecode#app" depends on it - in the nohoist list ["/_project_/@sharecode/app/react-native","/_project_/@sharecode/app/react-native/**","/_project_/@sharecode/app/react","/_project_/@sharecode/app/react/**","/_project_/@sharecode/app/react-query","/_project_/@sharecode/app/react-query/**"] info Disk size without dependencies: "356KB" info Disk size with unique dependencies: "404KB" info Disk size with transitive dependencies: "432KB" info Number of shared dependencies: 3 => Found "react@17.0.2" info Reasons this module exists - "_project_#@sharecode#web" depends on it - Hoisted from "_project_#@sharecode#web#react" info Disk size without dependencies: "356KB" info Disk size with unique dependencies: "404KB" info Disk size with transitive dependencies: "432KB" info Number of shared dependencies: 3 ✨ Done in 1.17s.Espero haber explicado el problema! Cualquier ayuda es apreciada :)
¡Gracias!