Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all 6213 articles
Browse latest View live

How to fix "error: bundling failed: SyntaxError: { path }\PinCode\index.ts: Exporting local "IPinCodeParams", which is not declared." in React-Native?

$
0
0

I created a new project. I have special folders for interfaces, types and etc. I will have a lot of them, so I import them into one file and export them from there. When I want to export multiple interfaces I get an error:

error: bundling failed: SyntaxError: C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\react-native\scripts\src\types\PinCode\index.ts: Exporting local "IPinCodeParams", which is not declared.  13 | }  14 |> 15 | export { PinStatus, IPinCodeParams }     |                     ^    at File.buildCodeFrameError (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\core\lib\transformation\file\file.js:261:12)    at NodePath.buildCodeFrameError (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\traverse\lib\path\index.js:157:21)    at getLocalMetadata (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\helper-module-transforms\lib\normalize-and-load-metadata.js:281:22)    at child.get.forEach.spec (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\helper-module-transforms\lib\normalize-and-load-metadata.js:315:11)    at Array.forEach (<anonymous>)    at programPath.get.forEach.child (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\helper-module-transforms\lib\normalize-and-load-metadata.js:307:33)    at Array.forEach (<anonymous>)    at getLocalExportMetadata (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\helper-module-transforms\lib\normalize-and-load-metadata.js:294:27)    at getModuleMetadata (C:\Users\QWERTY\Desktop\TestProjects\2019\TestProject\node_modules\@babel\helper-module-transforms\lib\normalize-and-load-metadata.js:86:21)

I have this folder structure:

android\ios\node_modules\src\--->constants\       |--->colors.ts       |--->fonts.ts       |--->index.ts--->router\       |--->index.ts--->screen\       |--->Splash\               |--->containers\                      |--->index.ts                      |--->SplashContainer.tsx               |--->views\                      |--->index.ts                      |--->SplashView.tsx               |--->index.tsx       |--->index.ts--->types\       |--->PinCode\               |--->index.tsx       |--->index.tsx--->App.tsx.babelrc***package.jsonrn-cli.config.jstsconfig.jsontslint.json

In the file "PinCode" I have an enum and an interface.

When I write so (all right):

export enum PinStatus {  New = 'new',  Confirm = 'confirm',  Unlock = 'unlock',  Edit = 'edit',}export interface IPinCodeParams {  status: PinStatus;  onComplete: () => void;  onClose?: () => void;  originalCode?: string;}

But when I write so (I get the error):

enum PinStatus {  New = 'new',  Confirm = 'confirm',  Unlock = 'unlock',  Edit = 'edit',}interface IPinCodeParams {  status: PinStatus;  onComplete: () => void;  onClose?: () => void;  originalCode?: string;}export { PinStatus, IPinCodeParams };

I have created some completely new projects, tried to rewrite this project several times, but nothing came out. I finally got this error anyway.

package.json

{"name": "TestProject","version": "0.0.1","private": true,"scripts": {"android": "node node_modules/react-native/local-cli/cli.js run-android","ios": "node node_modules/react-native/local-cli/cli.js run-ios","lint": "yarn tslint && yarn typecheck","tslint": "tslint --project tsconfig.json --config tslint.json src/**/*.ts{,x} --format stylish","typecheck": "tsc --project tsconfig.json --noEmit","postinstall": "typesync","type-sync": "typesync"  },"husky": {"hooks": {"pre-commit": "yarn lint","pre-push": "yarn lint"    }  },"dependencies": {"mobx": "^4.9.2","mobx-persist": "^0.4.1","mobx-react": "^5.4.3","react": "16.8.0","react-native": "0.58.4","react-native-vector-icons": "^6.2.0","react-navigation": "^2.18.1"  },"devDependencies": {"@babel/plugin-proposal-class-properties": "^7.3.0","@babel/plugin-proposal-decorators": "^7.3.0","@types/babel-core": "6.25.5","@types/jest": "24.0.0","@types/prettier": "^1.16.0","@types/react": "16.8.2","@types/react-native": "0.57.34","@types/react-native-vector-icons": "^4.6.4","@types/react-navigation": "^3.0.1","@types/react-test-renderer": "16.8.0","babel-core": "7.0.0-bridge.0","babel-jest": "24.1.0","babel-plugin-module-resolver": "^3.1.3","husky": "^1.3.1","jest": "24.1.0","jsc-android": "236355.1.1","metro-react-native-babel-preset": "0.51.1","mobx-logger": "^0.7.1","prettier": "^1.16.4","react-native-typescript-transformer": "^1.2.11","react-test-renderer": "16.6.3","tslint": "^5.12.1","tslint-config-prettier": "^1.18.0","tslint-eslint-rules": "^5.4.0","tslint-react": "^3.6.0","typescript": "^3.2.4","typesync": "^0.4.1"  },"jest": {"preset": "react-native"  }}

.babelrc

{"presets": ["module:metro-react-native-babel-preset",  ],"plugins": [    ["@babel/plugin-proposal-decorators",      {"legacy": true      }    ],"@babel/transform-react-jsx-source",    ["module-resolver",      {"root": ["/src"        ],"alias": {"@api": "./src/api","@actions": "./src/actions","@components": "./src/components","@constants": "./src/constants","@hocs": "./src/hocs","@managers": "./src/managers","@locales": "./src/locales","@reducers": "./src/reducers","@screens": "./src/screens","@static": "./src/static","@stores": "./src/stores","@styles": "./src/styles","@types": "./src/types","@utils": "./src/utils"        }      }    ],  ]}

tsconfing.json

{"compilerOptions": {"target": "es2015","module": "commonjs","moduleResolution": "node","jsx": "react-native","baseUrl": "./src","outDir": "./dist","allowSyntheticDefaultImports": true,"declaration": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"noEmit": true,"noImplicitAny": false,"noUnusedLocals": true,"noUnusedParameters": true,"pretty": true,"skipLibCheck": true,"sourceMap": true,"strict": true,"paths": {"@api": ["api"      ],"@actions": ["actions"      ],"@components": ["components"      ],"@constants": ["constants"      ],"@hocs": ["hocs"      ],"@managers": ["managers"      ],"@locales": ["locales"      ],"@reducers": ["reducers"      ],"@screens": ["screens"      ],"@static": ["static"      ],"@stores": ["stores"      ],"@styles": ["styles"      ],"@types": ["types"      ],"@utils": ["utils"      ]    }  },}

tslist.json

{"defaultSeverity": "error","extends": ["tslint-config-prettier","tslint-eslint-rules","tslint-react","tslint:latest"  ],"jsRules": {},"rules": {"await-promise": false,"interface-over-type-literal": false,"jsx-alignment": true,"jsx-boolean-value": false,"jsx-no-bind": true,"jsx-no-lambda": false,"max-classes-per-file": false,"member-access": false,"member-ordering": false,"no-constant-condition": false,"no-duplicate-imports": false,"no-empty": false,"no-implicit-dependencies": false,"no-submodule-imports": false,"object-literal-sort-keys": false,"ordered-imports": false,"quotemark": [      true,"single","jsx-single","avoid-escape"    ],"semicolon": [      true,"always"    ],"trailing-comma": [      true,      {"singleline": "never","multiline": "always"      }    ],"triple-equals": [      true,"allow-undefined-check"    ]  },"linterOptions": {"exclude": ["./src/typings/**/*.d.ts"    ]  },"rulesDirectory": []}

Reference to the source project (Github)

Why do I get this error? How to fix it?


React Native Typescript babel-plugin-module-resolver error: Cannot find module or its corresponding type declerations

$
0
0

I can use the module resolver with Javascript without any problem. Actually I can use it with Typescript without problem on runtime but on developing part I could not find the solution of Cannot find module or its corresponding type declerations problem.I'm looking for an answer which part am I doing it wrong?

Here are the files:

.babelrc

{"presets": ["module:metro-react-native-babel-preset"],"plugins": [    ["module-resolver",      {"root": ["./src"],"alias": [          { "@shared-components": "./shared/components" },          { "@shared-constants": "./shared/constants" },          { "@shared-theme": "./shared/theme" },          { "@font-size": "./shared/theme/font-size" },          { "@api": "./services/api/index" },          { "@fonts": "./shared/theme/fonts/index" },          { "@colors": "./shared/theme/colors" },          { "@theme": "./shared/theme/index" },          { "@services": "./services" },          { "@screens": "./screens" },          { "@utils": "./utils/" },          { "@assets": "./assets/" }        ],"extensions": [".js", ".jsx", ".ts", ".tsx"]      }    ]  ]}

tsconfig.json

{"compilerOptions": {"target": "esnext","module": "esnext","lib": ["esnext"],"allowJs": true,"jsx": "react-native","noEmit": true,"isolatedModules": true,"strict": true,"moduleResolution": "node","allowSyntheticDefaultImports": true,"esModuleInterop": true,    // ? Custom ones"skipLibCheck": true,"resolveJsonModule": true,"noImplicitAny": true,"strictNullChecks": true,"strictFunctionTypes": true,"strictPropertyInitialization": true,"noImplicitThis": true,"alwaysStrict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"forceConsistentCasingInFileNames": true,    // ? Babel Plugin Module Resolver"baseUrl": "./src","paths": {"@shared-components": ["./shared/components"],"@shared-constants": ["./shared/constants"],"@shared-theme": ["./shared/theme"],"@font-size": ["./shared/theme/font-size"],"@api": ["./services/api/index"],"@fonts": ["./shared/theme/fonts/index"],"@colors": ["./shared/theme/colors"],"@theme": ["./shared/theme/index"],"@services": ["./services"],"@screens": ["./screens"],"@utils": ["./utils/"],"@assets": ["./assets/"]    }  },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"  ]}

Usage in .tsx file

import HomeScreen from "@screens/home/HomeScreen";import SearchScreen from "@screens/search/SearchScreen";import DetailScreen from "@screens/detail/DetailScreen";

The errorimage

Thank you for the helping :)

The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

$
0
0

I am trying to customize my imports using babel. I am following this link:

https://medium.com/@leonardobrunolima/react-tips-working-with-relative-path-using-create-react-app-fe55c5f97a21

This is my config-overrides.js

const { injectBabelPlugin } = require('react-app-rewired');const rootImportConfig = ["root-import",    {        rootPathPrefix: "~",        rootPathSuffix: "src"    }];module.exports = config => injectBabelPlugin(rootImportConfig, config);

Package.json:

"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build",

Currently, this gives me an error that:The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

Hence, I installed

nom install customize-cra react-app-rewired --dev

and changed 'react-app-rewired' to 'customize-cra' in my js file as suggested here:https://github.com/arackaf/customize-cra#available-plugins

However, that still doesn't work since the injectBabelPlugin is also depreciated. What the function should I use here then? I tried the config files from here but it doesn't work from me either. It's src-functionality is also different.

https://github.com/timarney/react-app-rewired/issues/348

How can I fix my config file and imports? Instead of

import { ResultAlert } from '../../components/alerts/ResultAlert';

I want to do something like this:

import {ResultAlert} from '~/components';

typescript cast number type to never [duplicate]

$
0
0
r = Math.floor(Math.random() * arrOfCourse.length) + 1;if (arr.indexOf(r) === -1) arr.push(r);

I got this error on the r Argument of type 'number' is not assignable to parameter of type 'never'.

enter image description here

I'm suppose to cast r ? If I try to do:r:any = Math.floor(Math.random() * arrOfCourse.length) + 1; nothing change...

React Hooks - Invalid Hook Call

$
0
0

I am getting an 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 Hooks3. You might have more than one copy of React in the same app

This is my hook useParking:

import { Strings } from "..";import { get } from "../HTTPProvider";import { Lot } from ".";import { Moment } from "moment";import L from "leaflet";interface ApiResponse {  id: string;  fields: Lot;  createdTime: Moment | string;}const { apiUrl, apiKey } = Strings;const [error, setError] = useState(false);const getParkingLots = (setParkingLots: (l: Lot[]) => void) => {  get<{ records: ApiResponse[] }>(`${apiUrl}Parking%20Lots`, { apiKey })    .then((response) => {      console.log(response);      const data: Lot[] = [];      response.data.records.forEach((record) => {        const lat = record.fields.latitude;        const lon = record.fields.longitude;        if (lat && lon) record.fields.coordinates = L.latLng([lat, lon]);        data.push(record.fields);      });      setParkingLots(data);    })    .catch((error) => setError(error));  console.log(error);};export const useParkingLot = (): Lot[] => {  const [parkingLots, setParkingLots] = useState<Lot[]>([]);  useEffect(() => {    getParkingLots(setParkingLots);  }, [parkingLots]);  return parkingLots;};

I am trying to use the hook in my MainTabs component here:

import {  IonTabs,  IonTabBar,  IonTabButton,  IonIcon,  IonLabel,  IonRouterOutlet,} from "@ionic/react";import { map, business, calendarOutline, carOutline } from "ionicons/icons";import { Route, Redirect } from "react-router";import { CampusMap, Events, Buildings, ParkingLots } from "../../pages";import { useFakeEvent } from "../../DataProviders";import { useBuilding } from "../../DataProviders";import { useParkingLot } from "../../DataProviders";export const MainTabs: React.FC = () => {  const buildings = useBuilding();  const parkingLots = useParkingLot();  const [events, setEvents] = useState(useFakeEvent());  const [showName, setShowName] = useState(true);  const toggleName = () => {    console.log("resetName called");    setShowName(false);    return setTimeout(() => {      setShowName(true);    });  };  return (<IonTabs><IonRouterOutlet><Route path="/:tab(Events)" render={() => <Events />} exact={true} /><Route          path="/:tab(Map)"          render={() => (<CampusMap              buildings={buildings}              showName={showName}              parkingLots={parkingLots}              events={events}            />          )}          exact={true}        /><Route          path="/:tab(BuildingList)"          render={() => <Buildings buildings={buildings} />}          exact={true}        /><Route          path="/:tab(ParkingLotList)"          render={() => <ParkingLots parkingLots={parkingLots} />}          exact={true}        /><Route exact path="/" render={() => <Redirect to="/Map" />} /></IonRouterOutlet><IonTabBar slot="bottom"><IonTabButton tab="Map" href="/Map" onClick={toggleName}><IonIcon icon={map} /><IonLabel>Map</IonLabel></IonTabButton><IonTabButton tab="BuildingList" href="/BuildingList"><IonIcon icon={business} /><IonLabel>Buildings</IonLabel></IonTabButton><IonTabButton tab="Events" href="/Events"><IonIcon icon={calendarOutline} /><IonLabel>Events</IonLabel></IonTabButton><IonTabButton tab="ParkingList" href="/ParkingLotList"><IonIcon icon={carOutline} /><IonLabel>Parking Lots</IonLabel></IonTabButton></IonTabBar></IonTabs>  );};

I have checked my code against the Rules of Hook documentation and it doesn't seem like I am breaking any. I have also checked my dependencies and they all check out. So I'm not sure why I'm getting the error. Can anyone see what I am doing wrong here?

How can i sorting combobox items on React with Typescript?

$
0
0

I have a project and in project there is a year combobox. I will the year sorting(asc to desc or desc to asc).

enter image description here

I have a form utils and I call the utils in a component.

How to create type when using createRef for Animated.View in TypeScript

$
0
0

When creating a ref in a React Native component, Typescript complains about it if you don't provide the right type.

image = React.createRef();state = {    x: new Animated.Value(0),    y: new Animated.Value(0),};render() {    const {x, y} = this.state;    const imageStyle = {left: x, top: y};    return (<Animated.View            ref={this.image} // I got warning message here            {...this.responder}            style={[styles.draggable, imageStyle]}>            {this.props.children}</Animated.View>    )}const styles = StyleSheet.create({    draggable: {    position: 'absolute',    height: itemWidth,    width: itemWidth,    },  });

I got this warning

Type '{ children: ReactNode; style: ({ left: Value; top: Value; } | { position: "absolute"; height: number; width: number; })[]; current: unknown; ref: RefObject; }' is not assignable to type'IntrinsicAttributes & AnimatedProps & { children?: ReactNode; }'. Property 'ref' does not exist on type'IntrinsicAttributes & AnimatedProps & { children?: ReactNode; }'

createRef line needs to be something like image = React.createRef<some_type>();But I don't know how to create this some_type

React Native - Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

$
0
0

I have started getting this error Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication) since yesterday, my application was working and all of sudden it broke.

Google for hours most of them asked to -Delete your yarn.lock/package-json.lock file and run yarn/npm install.Then try clearing cache with npx react-native start --reset-cache but none of iit worked.

Tried deleting re-building the app but it fails with the same error.

My - index.js

/**

  • @format*/
import App from './App';import {name as appName} from './app.json';AppRegistry.registerComponent(appName, () => App);

react Native version

"react": "16.13.1","react-native": "0.63.2",

Dependencies all i have are

package.json

"dependencies": {"@ptomasroos/react-native-multi-slider": "^2.2.2","@react-native-community/datetimepicker": "^2.6.0","@react-native-community/masked-view": "^0.1.10","@react-native-community/picker": "^1.6.5","@react-native-community/slider": "^3.0.3","@react-navigation/bottom-tabs": "^5.7.2","@react-navigation/material-top-tabs": "^5.2.14","@react-navigation/native": "^5.7.2","@react-navigation/stack": "^5.8.0","@types/react-native-svg-charts": "^5.0.3","@types/react-redux": "^7.1.9","lottie-ios": "3.1.8","lottie-react-native": "^3.5.0","moment": "^2.27.0","react": "16.13.1","react-moment": "^0.9.7","react-native": "0.63.2","react-native-gesture-handler": "^1.7.0","react-native-reanimated": "^1.10.1","react-native-safe-area-context": "^3.1.1","react-native-screens": "^2.9.0","react-native-svg": "^12.1.0","react-native-svg-charts": "^5.4.0","react-native-swipe-list-view": "^3.2.3","react-native-swiper": "^1.6.0","react-native-tab-view": "^2.15.0","react-redux": "^7.2.1","redux": "^4.0.5"  }

ApolloClient configuration with createUploadLink and WebSocketLink

$
0
0

I want to be able to upload files from my React Native App for which I need to use createUploadLink but I am facing some problems configuring it.

My current setup looks like this:

import SInfo from "react-native-sensitive-info";import Config from "react-native-config";import { InMemoryCache, ApolloClient } from "apollo-boost";import { createHttpLink } from "apollo-link-http";import { createUploadLink } from "apollo-upload-client";import { WebSocketLink } from "apollo-link-ws";import { setContext } from "apollo-link-context";import { getMainDefinition } from "apollo-utilities";import { split } from "apollo-link";let token: any;const getToken = async () => {  if (token != null) {    return token;  }  token = await SInfo.getItem("ACCESS_TOKEN", {});  return token;};export const cache = new InMemoryCache();// Create a WebSocket link:const wsLink = new WebSocketLink({  uri: Config.SUBSCRIPTION_SERVER,  options: {    reconnect: true,  },});const httpLink = createHttpLink({ uri: Config.GRAPHQL_SERVER });const uploadLink = createUploadLink({ uri: Config.GRAPHQL_SERVER });const authLink = setContext(async (_, { headers }) => {  await getToken();  return {    headers: {      ...headers,      authorization: token ? `Bearer ${token}` : null,    },  };});const linkConcated = authLink.concat(httpLink);// using the ability to split links, you can send data to each link// depending on what kind of operation is being sentconst link = split(  // split based on operation type  ({ query }) => {    const definition = getMainDefinition(query);    return (      definition.kind === "OperationDefinition" &&      definition.operation === "subscription"    );  },  wsLink,  linkConcated);export const client = new ApolloClient({  link,  cache,});

I also tried the approach with ApolloLink.from([]) but it is not letting me add it. And also tried replacing it with createHttpLink as I need only one as per my understanding.

I get the following error:

const uploadLink: ApolloLinkArgument of type 'ApolloLink' is not assignable to parameter of type 'ApolloLink | RequestHandler'.  Type 'import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/@apollo/client/link/core/ApolloLink").ApolloLink' is not assignable to type 'import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/apollo-link/lib/link").ApolloLink'.    Types of property 'split' are incompatible.      Type '(test: (op: import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/@apollo/client/link/core/types").Operation) => boolean, left: import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/@apollo/client/link/core/ApolloLink").ApolloLink | import("/home/musayyab/Desktop/projects/Ta...' is not assignable to type '(test: (op: import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/apollo-link/lib/types").Operation) => boolean, left: import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/apollo-link/lib/link").ApolloLink | import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node...'.        Types of parameters 'test' and 'test' are incompatible.          Types of parameters 'op' and 'op' are incompatible.            Property 'toKey' is missing in type 'import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/@apollo/client/link/core/types").Operation' but required in type 'import("/home/musayyab/Desktop/projects/Talent/Native-App/app/node_modules/apollo-link/lib/types").Operation'.ts(2345)types.d.ts(24, 5): 'toKey' is declared here.

I would appreciate any help.

React Native + TypeORM and SQLite, SyntaxError: Invalid regular expression: invalid group specifier name

$
0
0

I'm starting to migrate my db in an application from Realm to TypeORM with SQLite but I'm getting an Invalid regular expression: invalid group specifier name error and I try to save an item into db with a relation.

This is de code I'm trying

 const produto = new Product(); produto.name = 'Produto 01'; produto.batches = []; const lote = new Batch(); lote.name = 'abc'; lote.amount = 10; lote.exp_date = new Date(); lote.price = 12.35; lote.status = 'tratado'; lote.product = produto; const productRepository = connection.getRepository(Product); const batchRepository = connection.getRepository(Batch); await productRepository.save(produto); await batchRepository.save(lote);

And those are my models

Model 1:

import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';import { Batch } from './Batch';@Entity({ name: 'Products' })export class Product {    @PrimaryGeneratedColumn('increment')    id: number;    @Column({        length: 50,    })    name: string;    @Column({        length: 20,        nullable: true,    })    code?: string;    @Column({        length: 30,        nullable: true,    })    store?: string;    @OneToMany((type) => Batch, (batch) => batch.product)    batches: Batch[];}

model 2:

import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';import { Product } from './Product';@Entity({ name: 'Batches' })export class Batch {    @PrimaryGeneratedColumn('increment')    id: number;    @Column()    name: string;    @Column({        type: 'date',        nullable: true,    })    exp_date: Date;    @Column({        type: 'int',        nullable: true,    })    amount?: number;    @Column({        type: 'double precision',        nullable: true,    })    price?: number;    @Column({        type: 'varchar',        default: 'Não tratado',    })    status?: string;    @ManyToOne((type) => Product, (product) => product.batches)    product: Product;}

I have tried change my node version when I was searching in the internet and I did't get anything different, I have also updated my metro-react-native-babel-preset to the lasted version and I'm still getting the same problem.

Can anyone help me?

React Native: 0.63.3.Node: 14.15.1Typeorm: 0.2.29

babel-plugin-module-resolver doesn't work with react native and typescript

$
0
0

I've been trying to implement module-resolver to my react native app but vs code underlines red the import lines

tsconfig.json file

{"compilerOptions": {"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"resolveJsonModule": true,"strict": true,"baseUrl": ".","paths": {"@utils/*": ["./src/utils/*"],"@components/*": ["./src/components/*"],"@constants/*": ["./src/constants/*"],"@data/*": ["./src/data/*"],"@hooks/*": ["./src/hooks/*"],"@redux/*:": ["./src/redux/*"],"@screens/*": ["./src/screens/*"],"@services/*": ["./src/services/*"],"@types/*": ["./src/types/*"]    }  }}

babel.config.js file

 ["module-resolver",            {              root: ["."],              extensions: [".ios.ts",".android.ts",".ts",".ios.tsx",".android.tsx",".tsx",".jsx",".js",".json",              ],              alias: {"@assets": "./assets","@components": "./src/components","@constants": "./src/constants","@data": "./src/data","@hooks": "./src/hooks","@redux": "./src/redux","@screens": "./src/screens","@services": "./src/services","@types": "./src/types","@utils": "./src/utils",              },            },          ],

My folder structure is like below

enter image description here

Error is like this

enter image description here

Code is working but how can I fix the editor error?

useEffect updating because redux state changed

$
0
0

In my app I have multiple useEffect hooks and a redux global state. Now depending on the change of the redux state the useEffect hook should run when the variable changes, which it does. My dispatch and useEffect hooks look like this:

const dispatch = useDispatch();const fetchOrder = useCallback((uuid: string) => dispatch(thunkFetchOrder(uuid)), [dispatch]);const fetchDebtor = useCallback((uuid: string | undefined) => dispatch(thunkFetchDebtor(uuid)), [dispatch]);const fetchOrderPayments = useCallback((uuid: string) => dispatch(thunkFetchOrderPayments(uuid)), [dispatch]);const orderInState: any = useSelector((state: RootState) => state.order);const debtorInState: any = useSelector((state: RootState) => state.debtor);useEffect(() => { fetchOrder(props.route.params.orderUuid); }, []);useEffect(() => { setOrder(orderInState); }, [orderInState.order.uuid]);useEffect(() => { setDebtor(debtorInState.debtor); console.log('update') }, [debtorInState.debtor.id]);useEffect(() => { setOrderPayments(orderInState.payments); }, [orderInState.payments]);

For example the useEffect hook with setOrder(orderInState) should only run when orderInState.order.uuid changes. However, it runs multiple times. The reducer for the order API call looks like this:

 const initialState: OrderState = {    order: {        uuid: ''    },    payments: []}export function orderReducer(    state = initialState,    action: OrderActionTypes): OrderState{    switch(action.type) {        case FETCH_ORDER_REQUEST:            if (state.order.uuid!== action.uuid) {                return {                    ...state,                    order: {}                }            } else {                return {                    ...state                }            }        case FETCH_ORDER:            return {                ...state,                order: action.payload            }        case FETCH_ORDER_PAYMENTS:            return {                ...state,                payments: action.payload            }        default:            return state;    }}

My redux global state looks like this:

export const rootReducer = combineReducers({    auth: authReducer,    error: errorReducer,    debtor: debtorReducer,    debtors: debtorsReducer,    order: orderReducer,    orders: ordersReducer,    payments: paymentsReducer,    roles: rolesReducer,    users: usersReducer,    credentials: credentialsReducer})

What am I doing wrong here?

React Native setState issue using an Object with TypeScript

$
0
0

I am having trouble with the setState of objects.My interface definition is as follows;

export interface IProjectData {  Id?: string,  Description?: string,  ProjectState?: string,}

I access the parameter I sent with RootStackParamList as follows.

function ProjectScreen({ route, navigation }: ProjectProps) {  const [project, setProject] = useState<IProjeData>(null)  useEffect(() => {    const sProject = JSON.stringify(route.params.project)    let myProject: IProjeData = JSON.parse(sProject)    console.log('myProject: ')    console.log(myProject)    setProject(myProject)    console.log('Project: ')    console.log(project)  }, [])  return (    ...    ...  )}

Consol output is as follows. Where am I going wrong? Why can't I assign a value to project?

myProject: {Id: "bd7acbea", Description"My Test Project", ProjectState"25/25"}Project: null

No overload match this call (Component React + Typescript)

$
0
0

In my placeholderTextColor the error of the title persist and do not find a solution

 import React from 'react';import { TextInputProps } from 'react-native';import { color } from 'react-native-reanimated';import { Container, TextInput, Icon } from './styles';interface InputProps extends TextInputProps {  name: string;  icon: string;}// todas as propriedades "rest" sao passadas para o TExt Input, no caso apenas o placeholderconst Input: React.FC<InputProps> = ({ name, icon, ...placeholder }) => (<Container><Icon name={icon} size={20} color="#666360" /><TextInput      keyboardAppearance="dark"      placeholderTextColor="#666360"      {...placeholder}    /></Container>);export default Input;

The error persists, if I remove spread operator the error is vanish, but it s not a solution

Full Error

(JSX attribute) placeholderTextColor?: string | typeof OpaqueColorValue | undefinedThe text color of the placeholder string

No overload matches this call.Overload 1 of 2, '(props: Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | "onLayout" | "pointerEvents" | "removeClippedSubviews" | ... 104 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.Type 'ColorValue' is not assignable to type 'string | unique symbol | undefined'.Type 'unique symbol' is not assignable to type 'string | unique symbol | undefined'.Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof TextInput, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof TextInput, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.Type 'ColorValue' is not assignable to type 'string | unique symbol | undefined'.Type 'unique symbol' is not assignable to type 'string | unique symbol | undefined'.ts(2769)index.d.ts(1626, 5): The expected type comes from property 'placeholderTextColor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | ... 107 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }'index.d.ts(1626, 5): The expected type comes from property 'placeholderTextColor' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextInputProps & RefAttributes, "ref" | "style" | "hitSlop" | ... 107 more ... | "showSoftInputOnFocus"> & Partial<...>, "ref" | ... 109 more ... | "showSoftInputOnFocus"> & { ...; } & { ...; } & { ...; }'

error An unexpected error occurred: "https://registry.yarnpkg.com/react-native-template-react-native-template-typescript: Not found"

$
0
0

After uninstalling the react-native-clii run this command to initiate a RN project with typescript template:

npx react-native init MyApp --template react-native-template-typescript

but i got this error:

warning jest > jest-cli > jest-config > jest-environment-jsdom > jsdom

left-pad@1.3.0: use String.prototype.padStart() error An unexpected error occurred:"https://registry.yarnpkg.com/react-native-template-react-native-template-typescript: Not found".info If you think this is a bug, please open .....
[1/2] Removing module react-native-template-react-native-template-typescript...
error This module isn't specified in a package.json file.
info Visit https://yarnpkg.com/en/docs/cli/remove for documentation about this command. warn Failed to clean up template temp files in node_modules/react-native-template-react-native-template-typescript. This is not a critical error, you can work on your app.
(node:8548) UnhandledPromiseRejectionWarning: Error: Command failed: yarn add react-native-template-react-native-template-typescript


Styled component throws weird typescript error

$
0
0

I have styled components and typescript in my RN Project

Typescript is throwing a weird error in one of my files, it says Element implicitly has 'any' type because expression of type 'string' can't be used to index 'ColorKeyType'

The affected code, the error is at the return theme.colors[color] part

const StyledText = styled(Text)<TextStyleProps>`  color: ${({ color, theme }) => {    if (color) {      return theme.colors[color] || color;    }    return theme.colors.text;  }}`;

My theme color is typed like:

interface ColorKeyType {  primary: string;  ... more colors like the one above}

then I use the type like:

{    colors: ColorKeyType;    fonts: {      families: {        primary: { [key in FontFamilyType]: string };      };      fontSize: { [key in FontSizeType]: number };      letterSpacing: number;    };}

Thanks in advance for any possible solutions!

decrementing after array mapping not working

$
0
0

I have a function "Next "that maps an array like in the example below and after incrementing the element I am doing something, but I also have another function "Prev" it pretty much does a similar mapping but in that function, I am decrementing the element. The Next function works fine but the Prev function doesn't, can someone please help me with this?

I am mapping an array of object

[   {"id":"v82b3a65","name":"Name"   },   {"id":"u0b26551","name":"Name2"   }]

my functions :

const Next = () => {  array.items.map((item, key, element) => {    var next = element[key ++];    setId(next.id);  });};const Prev = () => {  array.items.map((item, key, element) => {    var prev = element[key --];    setId(prev.id);  });};render(<View><Button title={'Prev'} onPress={Prev}/><Button title={'Next'} onPress={Next}/></View>)

I am using those functions in onPress of buttons

The result I need: on Next button press I want it to set setID = next objects id and on Prev button press I want to set setID = previous object id

React native typescript: usecontext functions not firing from inside child component

$
0
0

I have an issue when i try to use functions from a context inside a child component in a React native android app.

Below is my code for the context, and the form component im using it in (stripped down for brevity).

The "isFormOpen" object can be read no problem from inside any children that is wrapped in the provider, but when i try to call the "toggleForm" function from the same child component, it does nothing, no console errors either.

I have another context which is identical in structure and syntax except for vairable and function names etc, and that works perfectly, so im a bit confused as to why this does not work. I removed the other context, thinking there might be some type of conflict, but didnt solve it.

AccountContext.tsx

import React, { FC, createContext, useContext, useState } from 'react';interface AccountContextType {    isFormOpen: boolean,    toggleForm: (toggle: boolean) => void};export const AccountContext = createContext<AccountContextType>({    isFormOpen: false,    toggleForm: () => null});export const AccountContextProvider: FC = props => {    const [formOpen, setFormOpen] = useState<boolean>(false);    const toggleForm = (toggle: boolean) => {        setFormOpen(toggle);    }    const value: AccountContextType = {        isFormOpen: formOpen,        toggleForm    }    return (<AccountContext.Provider value={value}>            {props.children}</AccountContext.Provider>    )}export const useAccountContext = () => useContext(AccountContext);

TrackUploadForm.js

import React from 'react';import { SafeAreaView } from 'react-native';import { Button } from 'react-native-paper';import { useAccountContext } from '../contexts/AccountContext';import { AccountContextProvider } from '../contexts/AccountContext';const TrackUploadForm = () => {    const accountContext = useAccountContext();    return (<AccountContextProvider><SafeAreaView><Button onPress={() => accountContext.toggleForm(false)} mode='outlined'>Cancel</Button></SafeAreaView></AccountContextProvider>    )};export default TrackUploadForm;

How to make navigator screen component receive props passed to it

$
0
0

I have a stack navigator with a screen component:

const Stack = createStackNavigator<StackParamList>(); // StackParamList is custom typefunction Navigator() {  return (<Stack.Navigator initialRouteName="comp"><Stack.Screen name="comp" component={Component} /></Stack.Navigator>  );}

By default react-navigation pass props route and navigation to the screen component and to use these, the component must be defined like below as mentioned in official documentation:

export default function Component({route, navigation}){  // User `route` and `navigation` however you like it}

My IDE also prompts me to provide types for props something like:

export default function Component({route: RouteType, navigation: NavigationType})

Easiest way to do this is to specify RouteType and NavigationType as any but I would rather avoid it to get most out of static type checking. So, what is the best way to receive these route and navigation props? What exactly should be in RouteType and NavigationType excluding any?

Unable to download data from Firebase - TypeError: undefined is not an object

$
0
0

I'm trying to download user profiles from firebase and use them in a component. I'm having trouble with the async firebase function and useState. In the code below "profiles" repeatedly gets concatenated but it doesn't seem to update the "cards" prop in the Swiper component which still gets an empty array.

import * as React from 'react';import Swiper from 'react-native-deck-swiper'import { Card } from '../components/Card'import { View } from '../components/Themed';import firebaseSDK from '../database/firebase'export default function HomeScreen() {  const [profiles,setProfiles] = React.useState([])  firebaseSDK.db    .ref('userProfile')    .once('value')    .then((snapshot)=>{      //this line prints the profiles correctly      console.log("snapshot Val profiles : " + JSON.stringify(Object.values(snapshot.val())))      setProfiles(prevState => prevState.concat(Object.values(snapshot.val())))    })    return (<View style={styles.container}><Swiper      cards={profiles}      renderCard={Card}    />}

using this code I get

TypeError: undefined is not an object (evaluating 'cards.length')

Even though the console log shows "profiles" is continuously growing bigger as it gets repeatedly concatenated. What's the process to access the data correctly?

EDIT:

some more details about the code

the data I'm downloading looks like this :

{"id1":{    avatar: "https://placebear.com/200/300",    displayName: 'Fakeman Fakeaccount',    AboutMe: '16 miles away',    uid:1234  },"id2":{    avatar: "https://placebear.com/200/300",    displayName: 'Joanna, 19',    AboutMe: '2 miles away',    uid:1234  },"id3":{    avatar: "https://placebear.com/200/300",    displayName: 'Charlie, 32',    AboutMe: '24 miles away',    uid:1234  },}

cards takes an array of objects, which is why I initialized useState with an "[]" and I ran Object.values on snapshot.val() to turn it into an array.

The Card component:

export const Card = ({ avatar, displayName, AboutMe, uid }) => (<Tile    // imageSrc={avatar}    imageSrc={{uri:avatar}}    imageContainerStyle={styles.imageContainer}    activeOpacity={0.9}    title={displayName}    titleStyle={styles.title}    caption={AboutMe}    captionStyle={styles.caption}    containerStyle={styles.container}    key={uid}    featured  />)

Swiper takes an array of data (cards prop) and uses it to populate multiple Card components (renderCard prop)

Viewing all 6213 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>