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

Unable to resolve an image which is shared between web (react) and mobile (react-native) projects

$
0
0

I have a custom npm package created in directory web_with_weback (web react project). The package is built using webpack and contains one .png image. The package is loaded by using npm link inside another directory which is a react native project named mobile_with_metro. So in short, I want to have an npm package which among other things will share images from web to mobile. So to give you some context, here is how the two projects are setup.

The web project has the following structure.

enter image description here

Where the index.ts contains:

import TestImage from './testimage.png';export {    TestImage};

webpack.config.js

    const { CleanWebpackPlugin } = require('clean-webpack-plugin');const nodeExternals = require('webpack-node-externals');const CopyPlugin = require("copy-webpack-plugin");module.exports = {    entry: {        images: {import: './src/images/index.ts', filename: 'images/index.js'}    },    externals: [nodeExternals()],    output: {        libraryTarget: 'commonjs'    },    plugins: [        new CleanWebpackPlugin(),        new CopyPlugin({            patterns: [              { from: "src/images/index.d.ts", to: "images/index.d.ts" }            ],        }),    ],    module: {        rules: [            {                test: /\.(ts|tsx)$/,                exclude: /node_modules/,                use: ['babel-loader']            },            {                test: /\.(png|jpe?g|gif|svg)$/i,                type: 'asset/inline'            }        ]      }  }

I use webpack (v5.19.0). I use the latest feature from webapack asset/inline which is a replacement for the previous used url-loader.

dist folder after webpack build looks the following.

enter image description here

By using npm link in the dist folder and npm link @test/web_with_webpack in mobile_with_metro I make the built package available in the mobile app directory.

Now when I try to import the image and render it in an Image component in react native I get the following error:

    error: Error: Unable to resolve module `@test/web_with_webpack/images` from `App.tsx`: @test/web_with_webpack/images could not be found within the project or in these directories:  node_modules/@test/web_with_webpackIf you are sure the module exists, try these steps: 1. Clear watchman watches: watchman watch-del-all 2. Delete node_modules: rm -rf node_modules and run yarn install 3. Reset Metro's cache: yarn start --reset-cache 4. Remove the cache: rm -rf /tmp/metro-*    at ModuleResolver.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:186:15)    at ResolutionRequest.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)    at DependencyGraph.resolveDependency (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/node-haste/DependencyGraph.js:287:16)    at Object.resolve (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/lib/transformHelpers.js:267:42)    at /home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:434:31    at Array.map (<anonymous>)    at resolveDependencies (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:431:18)    at /home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:275:33    at Generator.next (<anonymous>)    at asyncGeneratorStep (/home/dpordan/dev/test_webpack_metro/mobile_with_metro/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)

Here is the react native App.tsx which imports the image.

    import React from 'react';    import {        Image    } from 'react-native';    import {TestImage} from '@test/web_with_webpack/images';    const App = () => {        return (<><Image source={{                    uri: TestImage                }}/></>        );    };

To me it seems that the metro bundler can't understand what webpack has generated as an image 'path'.

Is there anything that I am missing here?

EDIT:

I tried using it in another react web project (which is setup with CRA) and it works. So, there is something that metro bundler in react native does not understand in the built package.


Unsure what type my prop is in react native typescript

$
0
0

I am trying to implement typescript into my project and I am having issues giving prop types to my swipe prop. They are both the correct type but when giving this type I get an error on line 72:

style={[styles.container, isFirst && animatedCardStyle]}

The error says: Type'false | { transform: ({ [key: string]: Value; } | { rotate: AnimatedInterpolation; })[]; }' is not assignable to type 'false | Value | AnimatedInterpolation | RegisteredStyle | WithAnimatedObject | WithAnimatedArray<...> | readonly (false | ... 5 more ... | undefined)[] | null | undefined'.   Type '{ transform: ({ [key: string]: Animated.Value; } | { rotate: Animated.AnimatedInterpolation; })[]; }' is not assignable to type 'false | Value | AnimatedInterpolation | RegisteredStyle | WithAnimatedObject | WithAnimatedArray<...> | readonly (false | ... 5 more ... | undefined)[] | null | undefined'.     Type '{ transform: ({ [key: string]: Animated.Value; } | { rotate: Animated.AnimatedInterpolation; })[]; }' is not assignable to type 'WithAnimatedObject'.       The types returned by 'transform.pop()' are incompatible between these types.         Type '{ [key: string]: Value; } | { rotate: AnimatedInterpolation; } | undefined' is not assignable to type 'WithAnimatedObject | WithAnimatedObject | WithAnimatedObject | ... 10 more ... | undefined'.           Type '{ [key: string]: Value; }' is not assignable to type 'WithAnimatedObject | WithAnimatedObject | WithAnimatedObject | ... 10 more ... | undefined'.             Property 'matrix' is missing in type '{ [key: string]: Value; }' but required in type 'WithAnimatedObject'. index.d.ts(818, 5): 'matrix' is declared here.

I am really confused what this means, although my app runs and works I dont know the error, I can use the any type too and it clears this issue up too. Any help would be great!

import React, {useCallback} from 'react';    import {LinearGradient} from 'expo-linear-gradient';    import {Animated, Image, ImageSourcePropType, Text} from 'react-native';    import Choice from '../Choice';    import {ACTION_OFFSET} from '../Utils/constants';    import {styles} from './styles';    type Props = {        name: string,        source: ImageSourcePropType,        isFirst: boolean,        swipe: Animated.AnimatedValueXY,        tiltSign: Animated.AnimatedValue,    };    const Card = ({                      name,                      source,                      isFirst,                      swipe,                      tiltSign,                      ...rest                  }: Props) => {        const rotate = Animated.multiply(swipe.x, tiltSign).interpolate({            inputRange: [-ACTION_OFFSET, 0, ACTION_OFFSET],            outputRange: ['8deg', '0deg', '-8deg'],        });        const likeOpacity = swipe.x.interpolate({            inputRange: [25, ACTION_OFFSET],            outputRange: [0, 1],            extrapolate: 'clamp',        });        const nopeOpacity = swipe.x.interpolate({            inputRange: [-ACTION_OFFSET, -25],            outputRange: [1, 0],            extrapolate: 'clamp',        });        const animatedCardStyle = {            transform: [...swipe.getTranslateTransform(), {rotate}],        };        const renderChoice = useCallback(() => {            return (<><Animated.View                        style={[                            styles.choiceContainer,                            styles.likeContainer,                            {opacity: likeOpacity},                        ]}><Choice type="like"/></Animated.View><Animated.View                        style={[                            styles.choiceContainer,                            styles.nopeContainer,                            {opacity: nopeOpacity},                        ]}><Choice type="nope"/></Animated.View></>            );        }, [likeOpacity, nopeOpacity]);        return (<Animated.View                style={[styles.container, isFirst && animatedCardStyle]}                {...rest}><Image source={source} style={styles.image}/><LinearGradient                    colors={['transparent', 'rgba(0,0,0,0.9)']}                    style={styles.gradient}                /><Text style={styles.name}>{name}</Text>                {isFirst && renderChoice()}</Animated.View>        );    }    export default Card;

ApolloClient Typescript Higher Order Component issue (not assignable to type)

$
0
0

I'm trying to create a HOC in a React Native app, but I'm having issues getting the definitions to work.

interface IWithApolloClientComponentProps {    apolloClient: ApolloClient<any>;}export function withApolloClient<    P extends IWithApolloClientComponentProps,     R = Omit<P, keyof IWithApolloClientComponentProps>>(    Component: React.ComponentType<P>): React.ComponentType<R> {        return function BoundComponent(props: R) {            return <ApolloConsumer>{client => <Component {...props} apolloClient={client} />} . </ApolloConsumer>;    };}

My VSCode keeps giving the following error:

Type 'R & { apolloClient: ApolloClient<object>; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.  Type 'R & { apolloClient: ApolloClient<object>; }' is not assignable to type 'P'.'R & { apolloClient: ApolloClient<object>; }' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'IWithApolloClientComponentProps'.ts(2322)

Is anyone seeing something I'm doing terribly wrong here?

ReferenceError: Can't find variable: TextEncoder

$
0
0

I'm using VSCode/Typescript React 3.4.3 for a React Native project and I'm having troubles at runtime with TextEncoder

The ts code:

...var encoder = new TextEncoder();var b: Uint8Array = encoder.encode(newName);...

My tsconfig libs:

"module": "es2015","target": "es2015","jsx": "react","lib": ["es5", "es2017", "dom"]

This compile fines but it fails at runtime when it tries to create the instance of TextEncoder:

"ReferenceError: Can't find variable: TextEncoder"

I do not understand what is wrong here.

Any help appreciated

EDIT 1: Well the fact is that when you debug your JS code, it runs in Chrome which leads to success. But when you're not, you finish to discover that the JavaScriptCore neither support TextEncorder nor btoa.

So I have chosen to favor the use of npm modules (text-encoding and base-64):

import * as encoding from 'text-encoding';import {encode as btoa} from 'base-64'...var encoder = new encoding.TextEncoder();...

Problem with passing data between screens

$
0
0

I've got a problem with passing data between screens. Here is the screen where I'm taking input:

import React, {useState} from 'react'import {View, TextInput, Button, StyleSheet, TouchableWithoutFeedback, Keyboard} from 'react-native'import { useGlobal } from 'reactn';import Card from '../components/Card'import colors from '../constants/colors';type Props={navigation:any}const AddingScreen = (props:Props) =>{    let annmountAndProductToSend:any;    const [enteredProduct, setEnteredProduct] = useState<string>('');    const [ammount, setAmmount] = useState<any>('');    function enteredProductHandler(enteredText:string):void    {        setEnteredProduct(enteredText);    }    function ammountHandler(enteredText:any):void    {        let ammountAndProduct;        const amm = parseInt(enteredText);        if(isNaN(enteredText) || enteredText > 1)        {            setAmmount(enteredText);            ammountAndProduct = enteredText +''+ enteredProduct;            annmountAndProductToSend = ammountAndProduct;        }        else setAmmount('')    }    function confirmProduct()    {        props.navigation.navigate('Main',{input:enteredProduct});        setEnteredProduct('');        setAmmount('');    }    function returnToMainScreen()    {        props.navigation.navigate('Main')    }    return(<TouchableWithoutFeedback onPress = {() => {Keyboard.dismiss();}}><View style = {styles.inputContainer}><Card style = {styles.screen} ><TextInput blurOnSubmit autoCapitalize="none"                    placeholder="Nazwa przedmiotu"                     style={styles.input}                     onChangeText={enteredProductHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={enteredProduct}                    /><TextInput keyboardType = "number-pad"                     placeholder="Ilość"                     style={styles.input}                     onChangeText={ammountHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={ammount}                    /><View style = {styles.buttonContainer}><View style = {styles.button}><Button color = {colors.accent} title = 'Dodaj' onPress = {confirmProduct}/></View><View style = {styles.button}><Button title = 'Wyjdź' color = {colors.accent} onPress={returnToMainScreen}/></View></View></Card> </View></TouchableWithoutFeedback>    );};const styles = StyleSheet.create({    screen:    {        justifyContent:'center',        alignItems:'center',    },    inputContainer:{        flex: 0.5,         justifyContent:'center',        alignItems:'center'      },      input:{        height:30,        borderBottomColor: 'grey',        borderBottomWidth: 1,        marginVertical: 13,      },      buttonContainer:{          flexDirection:'row',          alignItems: 'center',          justifyContent: 'space-between' ,          width: '60%'      },      button:{          width:'40%',      }  });  export default AddingScreen;

And here is the screen, where i'm passing this data (input) to add it to FlatList:

import { StatusBar } from 'expo-status-bar';import React, {useState, useEffect} from 'react';import {   StyleSheet,   View,   Button,   FlatList,  Alert,} from 'react-native';import GoalItem from'../components/Goalitem';import Header from '../components/Header';import colors from '../constants/colors';type Props={  navigation:any}const MainScreen = (props:Props) =>{  let inputFromAdding = JSON.stringify(props.navigation.getParam('input'));  const [products, setProducts]  = useState<any>([]);  const [ammont, setAmmount] = useState<any>([])  function addProduct(goalTitle: any):any  {    setProducts([...products,{id: Math.random().toString(), value: goalTitle}]);     return products;  };  function removeGoalHandler(goalId:any):void  {    setProducts((courseGoals: any[]) =>     {      return courseGoals.filter((goal:any) => goal.id !== goalId);    });  };  function deleteListAlert():void  {    if(products.length >0)    {      Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?',        [{text: 'Tak', style: 'destructive', onPress: deleteList},         {text: 'Nie', style: 'cancel'}]);    }    else{      Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.',        [{text: 'Powrót', style: 'cancel'}]);    }  }  function deleteList()  {    setProducts('')  }  return (<View style = {styles.screen}><Header title="Lista zakupów"/><FlatList         keyExtractor={(item:any, index) => item.id}        data ={products}         renderItem ={itemData => (<GoalItem           id = {itemData.item.id}           onDelete = {removeGoalHandler}           title = {itemData.item.value}           />        )}      /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {colors.accent} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {colors.accent} title="+" onPress = {() => {            props.navigation.navigate('Adding')          }}/></View></View></View>  );}const styles = StyleSheet.create({  screen:{   flex:1,   backgroundColor: 'white',  },  button:{    width: 40,  },  button1:{    width: 90,  },  buttonPosition:{    padding:15,    alignItems: 'stretch',    justifyContent: 'space-between',    flexDirection:'row',    backgroundColor: colors.primary,  },});export default MainScreen;

So my data is here:

let inputFromAdding = JSON.stringify(props.navigation.getParam('input'));

I put it in console.log and it's sent right, but i've got a problem with adding it to

const [products, setProducts]  = useState<any>([]);

(products is my array of values)

I try to put a function in FlatList in prop data, that change the state with setProducts and returns products as my uploaded array, but i've got an error "Component Exception: Too many re-renders", also try to use globalState but it doesn't work. Maybe somebody can help me, thanks for help :)

Porblem with passing data between screen (Too many re-renders)

$
0
0

I've got a problem with passing data between screens. Here is the screen where I'm taking input:

import React, {useState} from 'react'import {View, TextInput, Button, StyleSheet, TouchableWithoutFeedback, Keyboard} from 'react-native'import { useGlobal } from 'reactn';import Card from '../components/Card'import colors from '../constants/colors';type Props={navigation:any}const AddingScreen = (props:Props) =>{    let annmountAndProductToSend:any;    const [enteredProduct, setEnteredProduct] = useState<string>('');    const [ammount, setAmmount] = useState<any>('');    function enteredProductHandler(enteredText:string):void    {        setEnteredProduct(enteredText);    }    function ammountHandler(enteredText:any):void    {        let ammountAndProduct;        const amm = parseInt(enteredText);        if(isNaN(enteredText) || enteredText > 1)        {            setAmmount(enteredText);            ammountAndProduct = enteredText +''+ enteredProduct;            annmountAndProductToSend = ammountAndProduct;        }        else setAmmount('')    }    function confirmProduct()    {        props.navigation.navigate('Main',{input:enteredProduct});        setEnteredProduct('');        setAmmount('');    }    function returnToMainScreen()    {        props.navigation.navigate('Main')    }    return(<TouchableWithoutFeedback onPress = {() => {Keyboard.dismiss();}}><View style = {styles.inputContainer}><Card style = {styles.screen} ><TextInput blurOnSubmit autoCapitalize="none"                    placeholder="Nazwa przedmiotu"                     style={styles.input}                     onChangeText={enteredProductHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={enteredProduct}                    /><TextInput keyboardType = "number-pad"                     placeholder="Ilość"                     style={styles.input}                     onChangeText={ammountHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={ammount}                    /><View style = {styles.buttonContainer}><View style = {styles.button}><Button color = {colors.accent} title = 'Dodaj' onPress = {confirmProduct}/></View><View style = {styles.button}><Button title = 'Wyjdź' color = {colors.accent} onPress={returnToMainScreen}/></View></View></Card> </View></TouchableWithoutFeedback>    );};const styles = StyleSheet.create({    screen:    {        justifyContent:'center',        alignItems:'center',    },    inputContainer:{        flex: 0.5,         justifyContent:'center',        alignItems:'center'      },      input:{        height:30,        borderBottomColor: 'grey',        borderBottomWidth: 1,        marginVertical: 13,      },      buttonContainer:{          flexDirection:'row',          alignItems: 'center',          justifyContent: 'space-between' ,          width: '60%'      },      button:{          width:'40%',      }  });  export default AddingScreen;

And here is the screen, where i'm passing this data (input) to add it to VirtualizedList:

import { StatusBar } from 'expo-status-bar';import React, {useState, useContext} from 'react';import {   StyleSheet,   View,   Button,   VirtualizedList,  Alert,} from 'react-native';import GoalItem from'../components/Goalitem';import Header from '../components/Header';import colors from '../constants/colors';type Props={  navigation:any}//setProducts([...products,{id: Math.random().toString(), value: props.navigation.getParam('input')}]); const MainScreen = (props:Props) =>{  const [products, setProducts]  = useState<any>([]);  const [didAddInput, setDidAddInput] = useState<boolean>(false);  const [ammont, setAmmount] = useState<any>([]);  function addProduct(input:string,oneadd:boolean){   setDidAddInput(oneadd);  if(didAddInput === true)  {    setProducts([...products,{id: Math.random().toString(), value: input}]);     return products;  }  setDidAddInput(false)  };  function removeGoalHandler(goalId:any):void  {    setProducts((courseGoals: any[]) =>     {      return courseGoals.filter((goal:any) => goal.id !== goalId);    });  };  function deleteListAlert():void  {    if(products.length >0)    {      Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?',        [{text: 'Tak', style: 'destructive', onPress: deleteList},         {text: 'Nie', style: 'cancel'}]);    }    else{      Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.',        [{text: 'Powrót', style: 'cancel'}]);    }  }  function deleteList()  {    setProducts('')  }  function count():number  {    return 50;  }  return (<View style = {styles.screen}><Header title="Lista zakupów"/><VirtualizedList         keyExtractor={(item:any, index) => item.id}        //data ={addProduct(value)}         getItem = {addProduct(JSON.stringify(props.navigation.getParam('input')),true)}        getItemCount = {count}        renderItem ={itemData => (<GoalItem           id = {itemData.item.id}           onDelete = {removeGoalHandler}           title = {itemData.item.value}           />        )}      /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {colors.accent} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {colors.accent} title="+" onPress = {() => {            props.navigation.navigate('Adding')          }}/></View></View></View>  );}const styles = StyleSheet.create({  screen:{   flex:1,   backgroundColor: 'white',  },  button:{    width: 40,  },  button1:{    width: 90,  },  buttonPosition:{    padding:15,    alignItems: 'stretch',    justifyContent: 'space-between',    flexDirection:'row',    backgroundColor: colors.primary,  },});export default MainScreen;

So my data is here:

getItem = {addProduct(JSON.stringify(props.navigation.getParam('input')),true)}

I put it in console.log and it's sent right, but i've got a problem with adding it to

const [products, setProducts]  = useState<any>([]);

(products is my array of values)

I try to put a second useState to avoid multiple adding by changing state to false after adding but it changes nothing, i've got an error "Component Exception: Too many re-renders", also try to use globalState but it doesn't work. Maybe there is another and better way to change the state with input data, thanks for help :)

Default Values with Interface in Arrow Function (TypeScript, React)

$
0
0

This question is specific to arrow functions. Is it possible to include the default values alongside an interface in the function parameters, and without resorting to Object.assign()?

interface Props {  someBoolean?: boolean;  anotherBoolean?: boolean;  children: any;}const DefaultValues = {  someBoolean: false,  anotherBoolean: false,}export const StackOverflow: React.FC<Props> = (_props: Props) => {  const props = Object.assign({}, _props, DefaultValues);  return <React.Fragment>{props.children}</React.Fragment>;};

Trouble re-rendering flatlist in functional component using extraData

$
0
0

I'm struggling to re-render a flatlist. I'm trying to use a boolean refreshToggle, that is fed into extraData, that is changed after the desired information is successfully fetched. The code below successfully fetches the data and changes the boolean (so changing to functional updates for the state, while perhaps better practice, doesn't seem like a solution) (I've checked that this is happening with various logs etc), but the flatlist doesn't re-render.

export default function transactions({ navigation }: { navigation: any }) {    const [paymentsBtnActive, setPaymentsBtnActive] = React.useState<boolean>(navigation.getParam('Pressed') == 'Payments');    const [requestsBtnActive, setRequestsBtnActive] = React.useState<boolean>(navigation.getParam('Pressed') == 'Requests');    const [refreshToggle, setRefreshToggle] = React.useState<boolean>(false);    let data: any[] = [];    async function getRequests() {        const body = { 'phone': GLOBAL.userInfo['phone']        }        const options = {            method: 'POST',            headers: { 'Content-Type': 'application/json'},            body: JSON.stringify(body)        }        let requests =  await fetch('http://3ef68e9c1352.ngrok.io/requests/user', options);        let requestsJSON = await requests.json();        data = requestsJSON['data'];    }        function renderItem(item: any) {        return (<Text>{item['item']['data']['date']}</Text>)    }    function listEmpty(){        return (<Text>Loading</Text>)    }    useEffect(() => {        (async function () {            await getRequests();            setRefreshToggle(!refreshToggle)        })()    }, [])    return (<SafeAreaView style = {styles.container}><View style = {{flexDirection: 'row', justifyContent: 'center'}}><TouchableOpacity style = { paymentsBtnActive ? styles.paymentsBtnActive : styles.paymentsBtnInactive } onPress = { () => { setRequestsBtnActive(paymentsBtnActive)                     setPaymentsBtnActive(!paymentsBtnActive) } } ><Text style = { paymentsBtnActive ? styles.whiteText : styles.redText }>Payments</Text></TouchableOpacity><TouchableOpacity style = { requestsBtnActive ? styles.requestsBtnActive : styles.requestsBtnInactive } onPress = { () => { setPaymentsBtnActive(requestsBtnActive)                    setRequestsBtnActive(!requestsBtnActive) } }  ><Text style = { requestsBtnActive ? styles.whiteText : styles.redText }>Requests</Text></TouchableOpacity></View><View style = {styles.summaryView}><FlatList                     data={data}                     renderItem={renderItem}                     ListEmptyComponent = {listEmpty}                    extraData = {refreshToggle}                /></View></SafeAreaView>    );

React Navigation V5 + Typescript Error: Property 'fullName' does not exist on type 'object'

$
0
0

My Goal:

I'm trying to add Typescript typings, but having an issue with route.params.fullName. When I console.log(route.params), the object { fullName: 'John Smith' } is logged. Why is Typescript having an issue with fullName?

The weird part is that the code works and when I navigate to the screen, the header title is updated with route.params.fullName.

Error:

Property 'fullName' does not exist on type 'object'.

Functional Component:

  // React Hooks: React Navigation  const route = useRoute();  // React Hooks: Lifecycle Methods  useEffect(() => {    console.log(route.params);    // React Navigation: Set Options    props.navigation.setOptions({      // ISSUE HERE      title: route.params.fullName,    });  }, [props.navigation, route.params]);

Props in custom components React native + Typescript

$
0
0

I've got a problem with access to onChangeText in my custom component.Here is the code of my component:

import React from 'react';import {TextInput, StyleSheet} from 'react-native';type Props={   style:any}const Input = (props:Props) =>{    return <TextInput {...props} style = {{...styles.input, ...props.style}} blurOnSubmit autoCorrect = {false} keyboardType = "number-pad" maxLength = {2} />}const styles = StyleSheet.create({    input:{        height:30,        borderBottomColor: 'grey',        borderBottomWidth: 1,        marginVertical: 10    }})export default Input;`

And here is the part of code in another file where i'm using it:

<Input style = {styles.input} onChangeText = {numberInputHandler} value = {enteredValue} />

OnChangeText is underlined and the error is Property 'onChangeText' does not exist on type 'IntrinsicAttributes & Props'. I see in a tutorial that after typing {...props} in my custom component inside there is access to its props, but guy is writing in js and I'm in in ts. Thanks for help!

useRef.current is undefined in a React Native functional component

$
0
0

I'm trying to focus a text input field once the user clicks a button. The code looks as follows:

const refName = React.useRef();const changeFocus = () => {    refName.current.focus();}

with the text input having an attribute ref defined as refName.This gives me an error (undefined is not an object (evaluating 'refName.current.focus')), and when I rewrite the changeFocus function as console.log(refName) this is what I get:

Object {"current": undefined,}

I'm not sure how else I'm supposed to define the reference or how else to approach this problem.Thanks

React Native (or React) listen to the style changes for the dark mode in separate ts modules

$
0
0

Goal: Implement dark mode in react native application.A little introduction to the system:File structure:

  • Profile.ts
  • ProfileCss.ts
  • constants.ts

In my application in order to separate styles from components, I moved them into .ts files and exported as modules.Example of StyleCss.ts:

import {StyleSheet} from 'react-native';import {Window, FixedCSS, hsize, wsize} from '../../entities/constants';export default StyleSheet.create({    loading: {        backgroundColor: FixedCSS.Colors.MainBackgroundColor,    }    ...});

All style-related constant values stored in constants.ts such as Colors, LineHeights, and etc. Also constants.ts contains a class called FixedCSS which has static properties:

export class FixedCSS {    static isDark = true;    static Colors = {        // Main Colors        RootColor: FixedCSS.isDark ? '#FF6666' : '#FF6666',        MainBackgroundColor: FixedCSS.isDark ? '#050505' : '#FFFFFF',        ...    }    ...}

isDark property of FixedCSS is supposed to be changed with the help of Switch component in Profile.ts

<Switch    value={darkMode}    onValueChange={value => {        this.setState({darkMode: value});    }}/>

The problem: How can I change isDark property in FixedCSS class so that it will affect the appearance of components. The most problematic aspect is that StyleCSS.ts files do not reflect to the change of isDark property in FixedCSS class, as they are exported only once when js bundle gets created.

How do i rerender my screen after deletion from list?

$
0
0

Hello I've been looking through several threads on stackoverflow but I haven't been able to solve my problem. I have an app where you can save movies to a watchlist. On this specific screen I want to display a users watchlist and give them the ability to delete it from the list. Currently the function is indeed deleting the movie from the list and removing it from firebase but i can't get my screen to rerender to visually represent the deletion.

This is the code right now:

export default function MovieWatchlistTab(props: any) {  let { movies } = props;  let movieWatchlist: any[] = [];  const [watchlistSnapshot, setWatchlistSnapshot] = useState();  const user: firebase.User = auth().currentUser;  const { email } = user;  const watchlistRef = firestore().collection("Watchlist");  useEffect(() => {    getWatchlistSnapshot();  }, []);  const getWatchlistSnapshot = async () => {    setWatchlistSnapshot(await watchlistRef.where("userId", "==", email).get());  };  const convertDataToArray = () => {    const convertedMovieList = [];    for (let movie in movies) {      let newMovie = {        backdrop: movies[movie].backdrop,        overview: movies[movie].overview,        release: movies[movie].release,        title: movies[movie].title,      };      convertedMovieList.push(newMovie);    }    movieWatchlist = convertedMovieList;  };  const renderMovieList = () => {    convertDataToArray();    return movieWatchlist.map((m) => {      const handleOnPressDelete = () => {        const documentRef = watchlistRef.doc(watchlistSnapshot.docs[0].id);        const FieldValue = firestore.FieldValue;        documentRef.set(          {            movies: {              [m.title]: FieldValue.delete(),            },          },          { merge: true }        );        movieWatchlist.splice(          movieWatchlist.indexOf(m),          movieWatchlist.indexOf(m) + 1        );        console.log("movieWatchlist", movieWatchlist);      };      const swipeButtons = [        {          text: "Delete",          color: "white",          backgroundColor: "#b9042c",          onPress: handleOnPressDelete,        },      ];      return (<Swipeout right={swipeButtons} backgroundColor={"#18181b"}><View key={m.title} style={{ marginTop: 10, flexDirection: "row" }}><Image              style={{ height: 113, width: 150 }}              source={{                uri: m.backdrop,              }}            /><View><Text                style={{                  flex: 1,                  color: "white",                  marginLeft: 10,                  fontSize: 17,                }}>                {m.title}</Text><Text style={{ flex: 1, color: "white", marginLeft: 10 }}>                Release: {m.release}</Text></View></View></Swipeout>      );    });  };  return (<View      style={{        flex: 1,        justifyContent: "center",        alignItems: "center",        backgroundColor: "#18181b",      }}><ScrollView        style={{ flex: 1 }}        contentContainerStyle={{          width: Dimensions.get("window").width,        }}>        {renderMovieList()}</ScrollView></View>  );}

I've been trying to play around with useStates and I think the answer is in that direction but I just can't seem to get it to work anyway. Any help would be appreciated!

Reference Type Within itself, TypeScript

$
0
0

I'm trying to pass types (screen param types) to a field based on the value (screenName) entered.

This is the navigation prop.

export interface IEditProfileStackNavigatorProps<RouteName extends keyof EditProfileRoutes> {  navigation: StackNavigationProp<EditProfileRoutes, RouteName>;  route: RouteProp<EditProfileRoutes, RouteName>;}

and the routes

export type EditProfileRoutes = {  Options: undefined;  Name: undefined;  Username: { token: string };  Bio: undefined;  Location: undefined;  VerifyUser: {    screenToNavigateTo: keyof Omit<EditProfileRoutes, 'VerifyUser'> | keyof ManageAccountRoutes;    params: any;  };};

I would like params to receive param types of a screen based on the screen name inserted in the navigation function.

navigation.navigate('VerifyUser', {  screenToNavigateTo: 'Username',  params: { some: 'value' } })}

so that if the screen inserted in screenToNavigateTo is username the param type will be { token: string } and for the rest it will be undefined.

My approach was doing something like

export type EditProfileRoutes = {  Options: undefined;  Name: undefined;  Username: { token: string };  Bio: undefined;  Location: undefined;  VerifyUser: {    screenToNavigateTo: keyof Omit<EditProfileRoutes, 'VerifyUser'> | keyof ManageAccountRoutes;    params?:EditProfileRoutes['VerifyUser']['screenToNavigateTo'];  };};

but this seems not to work

How to rewrite this function to a interface?

$
0
0

My goal is to write everything in interface, TypeScript. It's for React Native.

This is the function I am unable to put into an interface. The current solution is to put it outside the interface but the import would be ugly e.g import AudioRecorderModule, { addAudioRecorderEventListener } from '...'

export const addAudioRecorderEventListener = (  listener: (data: number[]) => void,) => eventEmitter.addListener('read', listener);

AudioRecorder.module.ts

import {NativeEventEmitter, NativeModules} from 'react-native';import AudioRecorderInterface from './AudioRecorder.d';const {AudioRecorderModule} = NativeModules;const eventEmitter = new NativeEventEmitter(AudioRecorderModule);export const addAudioRecorderEventListener = (  listener: (data: number[]) => void,) => eventEmitter.addListener('read', listener);export default AudioRecorderModule as AudioRecorderInterface;

AudioRecorder.d.ts

export default interface AudioRecorderInterface {  startAudioRecordingAsync(): Promise<null>;  stopAudioRecordingAsync(): Promise<null>;}

How to do AuthContext, createDataContext using Typescript for React Native Expo dev?

$
0
0

AuthContext.tsx

import createDataContext from './createDataContext';import serverApi from '../api/server';const authReducer = ({state, action}: any) => {     switch(action.type){        default:            return state;    }};const signup = () => {    return  async ({email, password}: any) => {        try{            const response = await serverApi.post('/signup', {email, password});            console.log(response.data)        }catch(err){            console.log(err.message);        }    };}const signin = ({dispatch}:any) => {    return ({email, password}: any) => {    };}const signout = ({dispatch}: any) => {    return () => {};}export const {Provider, Context} = createDataContext(    authReducer,    {signin, signout, signup},    {isSignedIn: false});

createDataContext

import React, { useReducer } from 'react';export default ({reducer, actions, defaultValue}: any) => {    const Context = React.createContext();    const Provider = ({ children }: any) => {        const [state, dispatch] = useReducer(reducer, defaultValue);        const boundActions: any = {};        for (let key in actions) {          boundActions[key] = actions[key](dispatch);        }        return (<Context.Provider value={{ state, ...boundActions }}>            {children}</Context.Provider>        );      };      return { Context, Provider };}

I copy the code from a video tutorial where react native app has been developed with js extension. But the project I am working on has tsx extension i.e. TypeScript.How to convert the above code so it will work in my typescript react native mobile app?

Is there a way to change the text of a element so that the text is different

$
0
0

I have a program where the text will change what is displayed depending on the state, the state can be 'loading', 'updating' etc. I was wondering if there was a way to do so without needing to refresh the page. So if the state is loading then it will display "loading your data" and the same for other states.

import "./styles.css";const status = {  loading: "loading your data",  updating: "updating your data",  updated: "your data is updated"};export default function App() {  const state = "updating";  return (<div className="App"><h1>{status.loading}</h1></div>  );}

Rome setup for react-native project (in TypeScript)

$
0
0

I've been following Rome for a while, and although there is some mention of it being used for react-native (here for example) I couldn't get it set up or find any tutorials for it.

Did anyone successfully configure it yet for their react-native project.
Or event for their RN project in TS?

Thanks in advance.
Much obliged.

Unable to resolve module with graphql

$
0
0

I just cant put my finger on why I can't get access to this import from the .tsx file.I understand that it is because the import is a .js file but I'm unsure as to how to fix it.

import { getUser } from '../src/graphql/queries';

file names:importing file: queries.js

file importing into: loginScreenView.tsx

Here is the error:

Cannot find module '../src/graphql' or its corresponding type declarations.ts(2307)

Ive read online about ways of fixing it using a types.d.ts file but I dont know how to apply that.

Please help

Amplify React-Native Auth sign in not staying signed in?

$
0
0

Using amplify and React-Native with Expo, my team built a backend and api layer before I was brought on, so I had to import them into amplify. Not sure if that's important, but due to how much amplify seems to not like this approach thought it might be relevant.

The amplify libraries were working until a few days ago, when suddenly the user would log in using the amplify Auth.signIn function, which would return the user object after awaiting it, and showed successful log in (ie, the object was returned with all of its info and tokens), but doesn't seem to be stored anywhere by amplify anymore. When an api call is made I get an Error: No credentials, applicationId or region error, and when I call Auth.currentSession or any other thing to see the current status of the auth info, they all return null, even within seconds of having received the valid login object.

the code to sign in looks like this:

                          const user = await Auth.signIn(username, password);                          console.log(JSON.stringify(user));

after this, the app moves to a new screen where it attempts to load some info needed via an appsync call, but then receives the above mentioned error, but even if we try something within the same screen, we get back the error or null user objects.

Viewing all 6288 articles
Browse latest View live


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