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

How to use AWS Amplify in React Native with Typescript Project?

$
0
0

I'm trying to add Amplify Authentication in my react native project which uses typescript.There is a package given in amplify documentation 'aws-amplify-react-native' which is used as a middleware to authenticate our application.But this package is only supported in projects which are based on javascript.For Typescript it shows an error like

Could not find a declaration file for module 'aws-amplify-react-native'.Try `npm install @types/aws-amplify-react-native` if it exists or add a new declaration (.d.ts) file containing `declare module 'aws-amplify-react-native';`

There is no package available like '@types/aws-amplify-react-native'

So anyone can help me out of this?


React Navigation v2: Conditionally navigate between two stacks

$
0
0

I have to use React Navigation v2, but I'm not sure if this is specifically related to that version. Anyway, I want my app to check connectivity and navigate to a top-level error screen if the user is not connected and otherwise navigate to the app itself. The error page is just one page, but the app should be its own navigation stack, so if the user leaves the error page and navigates back to the stack, the view should be maintained.

I'm struggling to figure out how to conditionally navigate at a top level.

My code is as follows:

const RootStack = createAppContainer(createSwitchNavigator({  NetworkCheck: { screen: NetworkCheck },  ErrorStack: { screen: ErrorStack },}));

This is used in the top level App component.

Then, I have the network checking component:

const NetworkCheck = () => {  const navigate = useNavigation();  const [isConnected, setIsConnected] = setState(true);  useEffect(async () => {    // checks connection periodically and calls `setIsConnected`  }, [isConnected]);  if (!isConnected) {    navigation.navigate('NetworkError');  }  return <NetworkCheckStack navigation={navigation} />}NetworkCheck.router = NetworkCheckStack.router;

NetworkCheckStack and ErrorStack are both createAppContainer(createStackNavigator( <various pages> )), similar to RootStack. ErrorStack contains the NetworkError page.

This essentially does work, but there are issues. The chief issue is that when the app navigates to ErrorStack, then the user navigates back, the page they were on in NetworkCheckStack is not preserves, i.e. it navigates back to the initial route and its route state is not maintained.

Additionally, I have to manually set the router and navigation, and I also get an error Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state. when navigating to NetworkError. These indicate to me that I may be going about this the wrong way.

How can I conditionally navigate between two stacks while maintaining the navigation of the stack itself?

Note: I have seen other questions and documentation that includes nesting stacks, but they don't include information on navigating from a higher level. If I don't do this, I would have to include the NetworkError navigation call on every screen.

React Native later Android and IOS file creation

$
0
0

I am writing applications with React Native. I am using it with typescript. I want to create an Android and IOS file. What can I do?

I tried the "react-native eject" command does not work.

React Native Version: react-native@0.62.2React-Dom Version: react-dom@16.11.0Expo Version: expo@38.0.9React Version: react@16.11.0

Folders

http://prnt.sc/vvk209

app.json

{"expo": {"name": "MyShop","slug": "MyShop","version": "1.0.0","orientation": "portrait","icon": "./assets/favicon.png","splash": {"image": "./assets/splash.png","resizeMode": "contain","backgroundColor": "#ffffff"    },"updates": {"fallbackToCacheTimeout": 0    },"assetBundlePatterns": ["**/*"    ],"ios": {"supportsTablet": true    },"web": {"favicon": "./assets/favicon.png"    }  }}

package.json

{"main": "node_modules/expo/AppEntry.js","scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web","eject": "expo eject","lint": "eslint --ext .ts,.tsx . --max-warnings 0","tsc": "tsc","ci": "yarn lint && yarn tsc"  },"dependencies": {"@expo/vector-icons": "^10.2.1","@react-native-community/hooks": "^2.6.0","@react-native-community/masked-view": "0.1.10","@react-navigation/drawer": "^5.9.3","@react-navigation/native": "^5.7.3","@react-navigation/stack": "^5.9.0","@shopify/restyle": "^1.2.0","expo": "~38.0.8","expo-asset": "~8.1.7","expo-constants": "~9.1.1","expo-font": "~8.2.1","expo-status-bar": "^1.0.0","formik": "^2.2.0","react": "~16.11.0","react-dom": "~16.11.0","react-native": "0.62.2","react-native-gesture-handler": "~1.6.0","react-native-keyboard-aware-scroll-view": "^0.9.3","react-native-reanimated": "~1.9.0","react-native-redash": "^14.6.0","react-native-safe-area-context": "~3.0.7","react-native-screens": "~2.9.0","react-native-svg": "12.1.0","react-native-web": "~0.11.7","yup": "^0.29.3"  },"devDependencies": {"@babel/core": "^7.8.6","@types/react": "~16.9.41","@types/react-native": "~0.62.13","@types/yup": "^0.29.8","typescript": "^4.0.0-beta"  },"private": true}

React Converting JSX application to Typescript

$
0
0

I am keeping my code short as possible to remove confusion, actually i am trying to convert my application built on React jsx to React Typescript thus (tsx file).

Error that i am receiving is - '[ts] Property 'state' does not exist on type 'App'.any ALSO same for '[ts] Property 'setState' does not exist on type 'App'.any'Please help me on this ...

interface STATE {  loading: boolean};interface PROPS {};export default class App extends Component<STATE, PROPS> {  constructor(props:any) {    super(props);    this.state = {      fruitsData : [],      loading: false    };  }  componentDidMount() {    this.setState({      loading: true    });    //Further functions present here plus call to service and binding the      data received to the array fruitsData  }

My package.json

 {"name": "example","version": "0.1.0","private": true,"devDependencies": {"@types/classnames": "^2.2.3","@types/node": "^4.0.35","classnames": "^2.2.5","gh-pages": "^0.12.0","react": "^15.5.4","react-dom": "^15.5.4","react-scripts": "0.9.5","typescript": "^2.7.0-insiders.20171214"  },"dependencies": {"@types/react": "^16.0.34","@types/react-dom": "^16.0.3","awesome-typescript-loader": "^3.4.1","react-search-box": "0.0.4"  },"scripts": {"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test --env=jsdom","eject": "react-scripts eject","predeploy": "npm run build","deploy": "gh-pages -d build"  }}

React.memo and typescript

$
0
0

I am working on a react native app. I am currently using Item component to display data in flatlist. But editor gives me an error for the second parameter of React.memo like below.

Type 'boolean | undefined' is not assignable to type 'boolean'.

Type 'undefined' is not assignable to type 'boolean'.

const Item = React.memo(    ({ icon, title }: any) => {        return (<Box                flexDirection="row"                paddingHorizontal="l"                justifyContent="space-between"                alignItems="center"                style={{ marginTop: 35 }}><Box flexDirection="row" alignItems="center" flex={1}>                    {icon}<Box marginLeft="l"><Text  variant="stackHeader">{title}</Text><Text                            fontSize={15}                            fontFamily="CrimsonRegular"                            style={{ color: '#575757' }}>                            Last update: 03/06/2020</Text></Box></Box><TouchableOpacity onPress={() => Clipboard.setString(title as string)}><FontAwesome5 name="copy" size={28} color="white" /></TouchableOpacity></Box>        );    },    (prev, next) => { // error here        if (prev.title === next.title) {            return true;        }    });

React native snack expo typescript error Parsing error: Unexpected token, expected ","

$
0
0

enter image description here

I don't understand what the problem is, if I remove the readonly it seems that the error message disappears.

How come you give the following message?

Link: expo

function areInputsEqual(  newInputs: readonly unknown[],  lastInputs: readonly unknown[]): boolean {  // Using for loop for speed. It generally performs better than array.every  // https://github.com/alexreardon/memoize-one/pull/59  for (let i = 0; i < newInputs.length; i++) {    // using shallow equality check    if (newInputs[i] !== lastInputs[i]) {      return false;    }  }  return true;}let lastArgs: unknown[] = [];let lastResult = 0;export default function mergeExtraData(...newArgs: unknown[]): number {  if (areInputsEqual(newArgs, lastArgs)) {    return lastResult;  }  // Something shallowly changed - return a new number from [0-10]  lastResult = lastResult === 10 ? 0 : lastResult + 1;  lastArgs = newArgs;  return lastResult;}

React Navigation Drawer doubling up URI parameter

$
0
0

I have setup a url for the Dashboard page at the NavigationContainer level, it contains an optional :id param.

const linking = {  prefixes: ['https://localhost:19006'],  config: {    screens: {      Dashboard: '/dashboard/:id?',    },  },};

My Drawer looks like this:

export function Dashboard() {  const route = useRoute();  const {height} = useWindowDimensions();  const {days, fetchPage} = useDays();  const initialRouteName = useMemo(() => {    if (route?.params && route?.params['id']) return route?.params['id'];    return days.length ? days[0].id : 'loading...';  }, [route.params, days]);  return (<View style={{height: height - 65}}><Drawer.Navigator        {...{          drawerContent: props => <ContentComponent {...{...props, fetchPage}} />,          drawerType: 'permanent',          openByDefault: true,          // drawerStyle: {width: '100%'},          initialRouteName,        }}>        {!days.length ? (<Drawer.Screen name={initialRouteName} component={View} />        ) : (          days.map(day => (<Drawer.Screen              key={day.id}              name={day.id}              initialParams={{id: day.id}}              component={Day}            />          ))        )}</Drawer.Navigator></View>  );}

The content of the drawer is being fetched. Everything works as expected to a point. You can load the page, and the default initialRoute is being set, and the url changes. I can click on the different drawer items. But what fails is when I refresh. The url :id duplicates, then when I refresh again, because there's no route for /dashboard/:id/:id it falls back to the home page.

How can I stop this doubling up, and have it so when I refresh the page it stays with the current :id?

Here's a gif:

enter image description here

How to animate expanding / collapsing a text preview in react native with Animated.View

$
0
0

I'm creating a text component that I want to be 2 lines by default, and if the user taps on it, it will expand to the full length, and if the user taps on it again, it will collapse back to 2 lines.

So far I have something like this in my return function:

<TouchableWithoutFeedback    onPress={() => {      toggleExpansion();    }}><Animated.View style={[{ height: animationHeight }]}><Text      style={styles.textStyle}      onLayout={event => setHeight(event.nativeEvent.layout.height)}      numberOfLines={numberOfLines}>      {longText}</Text></Animated.View></TouchableWithoutFeedback>

My state variables and toggleExpansion function look like this:

const [expanded, setExpanded] = useState(false);const [height, setHeight] = useState(0);const [numberOfLines, setNumberOfLines] = useState();const toggleExpansion = () => {  setExpanded(!expanded);  if (expanded) {    setNumberOfLines(undefined);  } else {    setNumberOfLines(2);  }};

So far this works to expand and collapse but I'm not sure how to set the Animated.timing function to animate it. I tried something like this:

const animationHeight = useRef(new Animated.Value(0)).current;useEffect(() => {  Animated.timing(animationHeight, {    duration: 1000,    toValue: height,    easing: Easing.linear  }).start();}, [height]);

but it didn't quite work. It doesn't display the text at all, and when I try initializing the new Animated.Value to a bigger number than the 2 line height (like 50), the height always gets truncated to 16 no matter how many times I expand and collapse. What's the best way to animate expanding and collapsing the text?


React native ref Property 'ref' does not exist on type 'IntrinsicAttributes &

$
0
0

I am getting the following error but I am not able to figure out how to fix it someone can help me out.

Below is also the link on expo with the complete code.

Error on <AppIntroSlider /> which is reported by snack expo

enter image description here

Example:

Type '{ ref: (ref: any) => any; data: { key: string; title: string;text: string; backgroundColor: string; }[]; renderItem: ({ item }:any) => Element; renderPagination: (activeIndex: number) => Element;scrollX: (scrollXList: any) => any; }' is not assignable to type'IntrinsicAttributes & { data: any[]; renderItem: (info:ListRenderItemInfo & { dimensions: { width: number; height:number; }; }) => ReactNode; renderSkipButton?: (() => ReactNode) |undefined; ... 19 more ...; scrollX?: ((a: any) => void) | undefined;} & FlatListProps<...> & { ...; }'. Property 'ref' does not exist ontype 'IntrinsicAttributes & { data: any[]; renderItem: (info:ListRenderItemInfo & { dimensions: { width: number; height:number; }; }) => ReactNode; renderSkipButton?: (() => ReactNode) |undefined; ... 19 more ...; scrollX?: ((a: any) => void) | undefined;} & FlatListProps<...> & { ...; }'.

Link: expo

  const slider = useRef(null);  ...<AppIntroSlider      ref={(ref: any) => (slider.current = ref)}      ...
type ItemTProps<ItemT> = {  data: ItemT[];  renderItem: (    info: ListRenderItemInfo<ItemT> & {      dimensions: { width: number; height: number };    }  ) => React.ReactNode;  renderSkipButton?: () => React.ReactNode;  renderNextButton?: () => React.ReactNode;  renderDoneButton?: () => React.ReactNode;  renderPrevButton?: () => React.ReactNode;  onSlideChange?: (a: number, b: number) => void;  onSkip?: () => void;  onDone?: () => void;  renderPagination?: (activeIndex: number) => React.ReactNode;  activeDotStyle: ViewStyle;  dotStyle: ViewStyle;  dotClickEnabled: boolean;  skipLabel: string;  doneLabel: string;  nextLabel: string;  prevLabel: string;  showDoneButton: boolean;  showNextButton: boolean;  showPrevButton: boolean;  showSkipButton: boolean;  bottomButton: boolean;  scrollX?: (a: any) => void;} & FlatListProps<ItemT>;const AppIntroSlider: FunctionComponent<ItemTProps<any>> = ({  data,  renderItem,  renderSkipButton,  renderNextButton,  renderDoneButton,  renderPrevButton,  onSlideChange,  onSkip,  onDone,  renderPagination,  activeDotStyle = {    backgroundColor: 'rgba(255, 255, 255, .9)',  },  dotStyle = {    backgroundColor: 'rgba(0, 0, 0, .2)',  },  dotClickEnabled = true,  skipLabel = 'Skip',  doneLabel = 'Done',  nextLabel = 'Next',  prevLabel = 'Back',  showDoneButton = true,  showNextButton = true,  showPrevButton = false,  showSkipButton = false,  bottomButton = false,  extraData,  scrollX,  ...otherProps}: any) => {

How to prevent multiple alert rendering using react native?

$
0
0

In my case, I am using alert component in render part, while I am executing app due to multiple time rendering my alert also calling twice and moretime. I have to prevent it, when alert is already displaying.

My Code Here:

return (          { alert rendering condition (<AlertPack          title= ""          subTitle=""          alertButtons={[            {              text: "ok",              onPress: () => {....}            },            {              text: "cancel",              onPress: () => {....},            },          ]}         />      )})

react useRef typescript child forwardedRef type

$
0
0

I'm forwarding a ref to Child component as per the react docs: https://reactjs.org/docs/forwarding-refs.html.

const userRef = useRef<TextInput>(null);interface IWrappedComponent {  ref?: RefObject<TextInput>;}const WrappedComponent = React.forwardRef((props: IWrappedComponent, ref) => {  return <LogProps {...props} forwardedRef={ref} />;});interface ILogProps {  innerRef?: RefObject<TextInput>;}

However I'm getting a type error for forwardedRef. I'm using RefObject<TextInput> for type, but am getting the following:

Type 'ForwardedRef<unknown>' is not assignable to type 'RefObject<TextInput>'.  Type 'null' is not assignable to type 'RefObject<TextInput>'.

How can I ignore react attributes from vscode intellisense for react native project?

$
0
0

I am so frustrated by seeing unrelated (React) intellisense suggestions while I am only working with react-native. I thought I am missing something in tsconfig.json however when I look at most popular typescript react native packages and pull them to check, I see the same intellisense suggestions in those repos too. Here's some examples:enter image description here

enter image description here

And this is tsconfig.json :

{"compilerOptions": {"declaration": true,"outDir": "./lib","strict": true,"jsx": "react-native","target": "es2019","module": "es6","moduleResolution": "node","allowSyntheticDefaultImports": true,"noImplicitAny": true,"experimentalDecorators": true,"preserveConstEnums": true,"sourceMap": true,"strictNullChecks": true,"skipDefaultLibCheck": true,"skipLibCheck": true,"noUnusedLocals": true,"noUnusedParameters": true,"noImplicitReturns": true,"noImplicitThis": true,"importHelpers": false,"alwaysStrict": true,"forceConsistentCasingInFileNames": true,"strictFunctionTypes": true,"resolveJsonModule": true,"noFallthroughCasesInSwitch": true,"strictPropertyInitialization": false,"lib": ["es6"],"typeRoots": ["./node_modules/@types", "./@types"]  },"include": ["src", "./types.d.ts"],"exclude": ["node_modules", "src/__tests__"]}

Any help will be appreciated much !

Initializing Text.defaultProps with Typescript

$
0
0

I just started rewriting my existing react-native project from js to typescript.To disable font scaling, I set Text.defaultProps.allowFontScaling to false at the beginning of App.js and it worked well.

import React from 'react';import { Text } from 'react-native';...if (Text.defaultProps == null) Text.defaultProps = {};Text.defaultProps.allowFontScaling=false; export default function App () {  . . .}

When I changed from App.js to App.tsx and ran tsc, I get following typescript error:

App.tsx:16:10 - error TS2339: Property 'defaultProps' does not exist on type 'typeof Text'.16 if (Text.defaultProps == null) Text.defaultProps = {};

I tried to search similar issues and typescript documents but failed. How can I solve this error?

Apollo refetch does not make a request after network error

$
0
0

Context

We are currently developing a React Native iOS app with a Graphql back-end. Within this app we would like to show the user a modal when there is no internet connection or when the API is down.

Since we are using Apollo and graphql-code-generator, we have a generated hook in the component that retrieves the data. We show the modal when the hook returns a network error. If a network error has been found, the refetch method from the hook is used to poll and see whether the network or API is back up.

The Problem

This unfortunately does not seem to work, calls to the refetch method after the network has been reestablished do not result in requests. The refetch method also throws a network error.

Code

function useConnectionStatusPolling() {  // 'useData' is a custom wrapper around the generated hook, that maps and deserialises fields.  const { loading, refetch, error } = useData();  // While refreshing, error.networkError is reset.But we would like  // to keep the error status around until the request works again.  //  // For that, we keep the error in the mutable reference, and update it  // only when the status it not loading. For loading, keep the  // previous value.  const networkError = useRef(false);  if (!loading) {    networkError.current = !!error?.networkError;  }  // Polling is done manually via useInterval because the builtin polling stops  // if a network error is thrown which we want to ignore in our case.  useInterval(refetch, networkError.current ? 5000 : "pause");  return networkError.current;}
/** * Executes a callback at each interval. * https://overreacted.io/making-setinterval-declarative-with-react-hooks/ * @param callback Method to execute after each delay. * @param delay Time in miliseconds. */export function useInterval(callback: () => void, delay: number | "pause") {  const savedCallback = useRef<() => void>();  // Remember the latest callback.  useEffect(() => {    savedCallback.current = callback;  }, [callback]);  // Set up the interval.  useEffect(() => {    function tick() {      savedCallback.current?.();    }    if (delay !== "pause") {      const id = setInterval(tick, delay);      return () => clearInterval(id);    }  }, [delay]);}

Research & Attempts

We did find out that the error is not cleared as specified in this article. So this hook won't will keep showing the no internet modal and making requests. However this problem still persists after this change, the refetch method just does not make a request to the API. We also tried clearing the cache, but to no avail unfortunately. So I am not really sure what to try at the moment in order to make this work, any advice would be greatly appreciated!

Prop type for drawerContent in a nested drawer navigator

$
0
0

My navigigation is

Stack  Drawer    DrawerScreen1    DrawerScreen2  StackScreen

The Drawer.Navigator accepts a prop drawerContent.

drawerContent accepts a function of type (props) => React.Element.

The type of props.navigator in drawerContent function is DrawerNavigationHelpers. This does not allow navigation.push.

How can we assign a type so that props.navigator has both drawer and stack methods?


ReactNative queryString not formatting correctly

$
0
0

I am trying to fetch data based on a query. However, if i pass a query to my api call and format the queryString. The result will look like this:

Object {"DE": null,"limit": 10,"offset": 0,}

When fomratted correctly, the Object should look like this:

Object {"query": "DE","limit": 10,"offset": 0,}

(For showcasing my issue I set a default value fro my query). My API call looks like this:

export function thunkFetchOrders(    query = 'DE',    offset = 0,    limit = 10,    filters = {}) {    return async (dispatch: any) => {        if (offset === 0) {            dispatch(                resetOrders()            )        }        let requestParams = {            offset,            limit,        }        requestParams = {...requestParams, ...setFilter(filters)}        if (query) {            requestParams = {...requestParams, ...queryString.parse(query)}        }        try {            const res = await axios.get(`/orders`, {params: requestParams})            await dispatch(                fetchOrders(                    res.data,                    limit,                    offset,                    filters                )            )            }        catch (error) {            await dispatch(thunkFetchError(error));        }    }}

What am I doing wrong here?

react-navigation 5.x: TS2345: Argument of type ' ... ' is not assignable to parameter of type '... '

$
0
0

I have migrated from react-navigation 4.x to 5.x. Since I am using typescript, I am trying to add the types. I should mention that the functionality works perfectly fine. However, I am getting this typescript error:

enter image description here

TS2345: Argument of type '["PaperPlaneDetails", { paperPlane: PaperPlaneInterface; returnRoute: string; }]' is not assignable to parameter of type '["PaperPlaneDetails"] | ["PaperPlaneDetails", undefined]'.   Type '["PaperPlaneDetails", { paperPlane: PaperPlaneInterface; returnRoute: string; }]' is not assignable to type '["PaperPlaneDetails", undefined]'.     Type '{ paperPlane: PaperPlaneInterface; returnRoute: string; }' is not assignable to type 'undefined'.
//OpenPaperPlaneModal.tsx located in ReceivePaperPlaneScreen.tsxtype AppStackParamList = {  EditProfile: undefined;  Introduction: undefined;  PaperPlaneDetails: undefined;  Logout: undefined;  DebugScreen: undefined;  PaperPlane: undefined;  MyProfileScreen: undefined;  FollowersScreen: undefined;  FollowingScreen: undefined;  UsersProfileScreen: undefined;  SettingsScreen: undefined;  CommentsScreen: undefined;};type PaperPlaneBottomTabNavigatorParamList = {  TakePaperPlaneScreen: undefined;  ReceivePaperPlaneScreen: undefined;  NotificationScreen: undefined;};type OpenPaperPlaneModalNavigationProp = CompositeNavigationProp<  BottomTabNavigationProp<    PaperPlaneBottomTabNavigatorParamList,'ReceivePaperPlaneScreen'>,  StackNavigationProp<AppStackParamList>>;export default function OpenPaperPlaneModal(props) {  const navigation = useNavigation<OpenPaperPlaneModalNavigationProp>();  navigation.navigate('PaperPlaneDetails', {    paperPlane: props.paperPlane,    returnRoute: 'ReceivePaperPlaneScreen',  });}
"typescript": '3.8.3'"@react-navigation/bottom-tabs": "^5.3.1","@react-navigation/native": "^5.2.1","@react-navigation/stack": "^5.2.16",

Accessing nested json data with Hooks

$
0
0

I am having trouble filtering the json that I have in React Typescript Using Hooks.I have a JSON that comes from a fetch and it looks like this:

[{"dealer 1":    [    {"name": "SERVICE 1""city": "NORTH CANTON""phone": "3306596372""isOpen": "true"    },    {"name": "SERVICE 2""city": "OHIO""phone": "3306596372""isOpen": "true"    }    ]},{"dealer 2":    [    {"name": "SERVICE A""city": "WASHINGTON""phone": "3306596375""isOpen": "true"    },    {"name": "SERVICE B""city": "SEATTLE""phone": "3306596376""isOpen": "true"    }    ]}]

my code for fetching the api is:

useEffect(() => {    axios.get("API URL here")        .then(res => {            console.log(res)            setCTSN(res.data)        });}, []);

and I wanted to return all open dealers so I need to filter it by "isOpen=true"

const isOpen = 'true'const result = OPEN    .map(item => ({        ...item, //Spread types may only be created from object types.ts(2698)        children: item.children            .filter(child => child.value.includes(isOpen.toLowerCase()))    }))    .filter(item => item.children.length > 0)console.log(result)

but I am getting an error with the '...item' and I'm not sure if I am doing it correctly in React Typescript.

Can someone help me?

react-i18next on React Native No overload matches this call typescript

$
0
0

Iam trying to configure react-i18next 11.8.2 in my React Native app with typescript 4.1.2:

i18n.use(initReactI18next).init({  resources: {    en,    es,  },  lng: 'es',  fallbackLng: 'es',  interpolation: {    escapeValue: false,  },});

with two resources files (en, es).

But i am getting an typescript error with the TFunction interface using the useTranslation hook:

const {t, i18n} = useTranslation(['SelectLanguage']);]<StyledLabel>{t('SelectLanguage:title')}</StyledLabel>

The error:

No overload matches this call.  Overload 1 of 2, '(props: Pick<Pick<TextProps & RefAttributes<Text>, "key" | "ref" | "style" | "onLayout" | "testID" | "nativeID" | "accessible" | "accessibilityActions" | ... 35 more ... | "dataDetectorType"> & Partial<...>, "key" | ... 42 more ... | "dataDetectorType"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.    Type 'TFunctionResult' is not assignable to type 'string | number | TextElement | ChildElement[] | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | ... 20 more ... | undefined'.      Type 'null' is not assignable to type 'string | number | TextElement | ChildElement[] | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | ... 20 more ... | undefined'.  Overload 2 of 2, '(props: StyledComponentPropsWithAs<typeof Text, any, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof Text, any, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.    Type 'TFunctionResult' is not assignable to type 'string | number | TextElement | ChildElement[] | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | ... 20 more ... | undefined'.      Type 'null' is not assignable to type 'string | number | TextElement | ChildElement[] | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | ... 20 more ... | undefined'.ts(2769)text.component.d.ts(15, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextProps & RefAttributes<Text>, "key" | "ref" | "style" | "onLayout" | "testID" | ... 38 more ... | "dataDetectorType"> & Partial<...>, "key" | ... 42 more ... | "dataDetectorType"> & { ...; } & { ...; } & { ...; }'text.component.d.ts(15, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & Pick<Pick<TextProps & RefAttributes<Text>, "key" | "ref" | "style" | "onLayout" | "testID" | ... 38 more ... | "dataDetectorType"> & Partial<...>, "key" | ... 42 more ... | "dataDetectorType"> & { ...; } & { ...; } & { ...; }'

I can solve this error by parsing the result of the i18n translation like this:

<StyledLabel>{t<string>('SelectLanguage:title')}</StyledLabel>

Do you have any idea of why this is happening? i think it could be the StyledLabel props, it is just an styled component of a @ui-kitten/components Text

import styled from 'styled-components/native';import {Text} from '@ui-kitten/components';export const StyledLabel = styled(Text)`  margin-bottom: 5px;`;

the text.component of UI Kitten:

export declare class Text extends React.Component<TextProps> {    render(): React.ReactElement<RNTextProps>;}export {};

TypeError: Cannot read property 'objects' of undefined Jest

$
0
0

I get this error while running a jest test that has realm object called in it ie in the component. The component that is being tested it a react-native typescript component. Any Idea on how to mock the realm object in the jest?

import 'react-native';import React from 'react';import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store';import { mount } from 'enzyme';import renderer from 'react-test-renderer';import SendBird from 'sendbird';import { Actions } from 'react-native-router-flux';import Chat from '../src/pages/chat/chat';import offline from '../src/utils/OfflineNotification';const mockStore = configureMockStore();const store = mockStore({authReducer: {loggedInUserDetails: {  username: 'Test user',  attributes: { email: 'test@fissionlabs.com', 'custom-name': 'asd123' }, },},companyProfile: {companiesListBuffer: [],currentDisplayedCompany: {  startup: {    name: '',    keywords: '',    labels: '',    deadline: '',    elevator_pitch: '',    total_addressable_market: '',    notable_customers: '',    founding_team: '',    lead_investor: '',    interested_investors: '',    round_deadline: '',    pitch_deck: '',    metrics: '',    commited: '',    round: '',    questions: '',    stage: '',    logo: '',  }, },},profileData: { profileData: { name: 'Test profile' },},});jest.useFakeTimers();jest.mock('sendbird');jest.mock('react-native-popup-menu');jest.mock('@react-native-community/async-storage', () => {return {getItem: jest.fn(() => Promise.resolve()),};});jest.mock('react-native-image-picker', () => {return {showImagePicker: jest.fn(() => Promise.resolve()),};});jest.mock('react-native-device-info', () => {return {hasNotch: jest.fn(),};});jest.mock('react-native-safe-area', () => {return {getSafeAreaInsetsForRootView: jest.fn(() => Promise.resolve()),};});describe('Test Connectors', () => {let wrapper = null;let instance = null;const props = { saveCurrentCompanyAction: jest.fn(), getOnPress: jest.fn(), closeChat: jest.fn(), direction: 'left', chatInfoData: {  data: { startupId: 'wed23242' },  customType: 'Custom', }, continueMessage: false, previousMessage: {  value: {    __sender: {      userId: 123,    },  },}, nextMessage: {  value: {    __sender: {      userId: 123,    },  }, }, message: {  _sender: {    metaData: {      role: 'founder',    },    userId: 1,  },  data: '', }, chatInfo: {  userId: 22,  accessToken: '',  chatId: 'chat01', }, messageStatus: 'delivered',};beforeEach(() => {console.error = () => {};console.warn = () => {};jest.mock('react-redux', () => {  return {    connect: (mapStateToProps, mapDispatchToProps) => (ReactComponent) =>  ({      mapStateToProps,      mapDispatchToProps,      ReactComponent,    }),    Provider: ({ children }) => children,  }; }); wrapper = mount(<Provider store={store}><Chat {...props} /></Provider>, )  .childAt(0)  .childAt(0); instance = wrapper.instance(); }); it.only('should render successfully', () => {  expect(wrapper).toBeTruthy(); });

Here The wrapper is always undefined. Is there Any way that I can mock realm as I have mocked all the other imports? Thanks

Viewing all 6213 articles
Browse latest View live


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