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

React Native: Flip card animation always shows the same side of the card

$
0
0

I am new to React Native. I tried to create flip card animation and I was following a tutorial, and created the animation but it shows only one side of the card when the animation ends. I think the problem comes from my style but couldn't figure out how to fix this.

My current code is this.

const CardFlip = ({ navigation, route }: Props) => {  const animatedValue = new Animated.Value(0);  const [val, setVal] = useState(0);  const frontInterpolate = animatedValue.interpolate({    inputRange: [0, 180],    outputRange: ['0deg', '180deg'],  });  const backInterpolate = animatedValue.interpolate({    inputRange: [0, 180],    outputRange: ['180deg', '360deg'],  });  const frontAnimatedStyle = {    transform: [      { rotateY: frontInterpolate }    ]  };  const backAnimatedStyle = {    transform: [      { rotateY: backInterpolate }    ]  };  useEffect(() => {    animatedValue.addListener(({ value }) => {      setVal(value);    });  });  const flipCard = (): void => {    Animated.spring(animatedValue, {      toValue: val >= 90 ? 0 : 180,      friction: 8,      tension: 10,      useNativeDriver: true,    }).start();  };  return (<View style={styles.screen}><View style={styles.cardWrapper}><Animated.View style={[styles.card, frontAnimatedStyle]}><Text style={styles.text}>            Front</Text></Animated.View><Animated.View style={[styles.cardBack, backAnimatedStyle]}><Text style={styles.text}>            Back</Text></Animated.View>             </View><View style={styles.buttonWrapper}><TouchableOpacity          style={styles.flipCardButton}><Icon             name="visibility"            type="material"            color="#FFFFFF"            size={30}            onPress={() => flipCard()}          /></TouchableOpacity></View></View>  );};const styles = StyleSheet.create({  screen: {    height: '100%',    width: '100%',    top: 0,    left: 0,    backgroundColor: '#F7F3EC',  },  cardWrapper: {    alignItems: 'center',  },  card: {    position: 'absolute',    height: 480,    width: 320,    top: 40,    paddingTop: 45,    paddingHorizontal: 25,    backgroundColor: '#F9D6E2',    borderRadius: 7,    borderWidth: 0,    elevation: 6,    backfaceVisibility: 'hidden',  },  cardBack: {    position: 'absolute',    height: 480,    width: 320,    top: 40,    paddingTop: 45,    paddingHorizontal: 25,    backgroundColor: '#F9D6E2',    borderRadius: 7,    borderWidth: 0,    elevation: 6,    backfaceVisibility: 'hidden',  },  text: {    fontSize: 24,  },  buttonWrapper: {    position: 'absolute',    alignItems: 'center',    width: '100%',    height: 60,    bottom: 0,  },  flipCardButton: {    alignItems: 'center',    justifyContent: 'center',    height: 60,    width: 60,    position: 'absolute',    bottom: 10,    borderRadius: 100,    borderWidth: 0,    elevation: 6,    backgroundColor: '#EF5350',  }});

And the animation is like this.

enter image description here

How can I fix this?


How to pass props to StyleSheet on custom view in React Native?

$
0
0

So, I have a custom view. On that view, besides taking the children components, I also wanna take backgroundColor and some other StyleSheet property so I can style it depends on the screens.

This is the App.tsx.

export const MainScreen = ({}: Props) => {  return (<CustomView backgroundColor={"#000"}><Text>Example</Text></CustomView>  );};

And this is the CustomView.tsx

type Props = {  children: React.ReactNode;  backgroundColor: string;};export const CustomView = ({ children, backgroundColor }: Props) => {  return <View style={styles.container}>{children}</View>;};const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: "center",    alignItems: "center",  },});

Say, I wanna change the background color for this screen to #000 like on the codes above. But, I don't know how to handle the props on the CustomView so it can change the backgroundColor.

I tried writing this code

return <View style={styles.container, {backgroundColor: backgroundColor}}>{children}</View>;

But it overwrites the styles.container. On the other hand, if I write this

return <View style={{backgroundColor: backgroundColor}, styles.container}>{children}</View>;

It always throws the error that the left side of comma (the backgroundColor itself) is unused and has no side effects.

So, what should I do? How can I pass the props to handle the StyleSheet?

React Native issue : [Unhandled promise rejection: TypeError: f is not a function. (In 'f()', 'f' is undefined)]

$
0
0

I am trying to make a login system using states and fetch so that the user can receive his valid token and then put it in storage with Async Storage.I am still in the phase of communication with the API (expressjs). Everything works for the moment when I enter the email and the password I do receive the token in json but I have a warning type error which tells me:

[Unhandled promise rejection: TypeError: f is not a function. (In 'f()', 'f' is undefined)]

My code is very simple for the moment (I have absolutely no idea where it comes from):

const onSubmit = () => {    setLoading(true)    fetch('http://192.168.1.36:3000/api/users/login', {      method: 'POST',      headers: {        Accept: 'application/json','Content-Type': 'application/json'      },      body: JSON.stringify({        email: email,        password: password      })    })    .then((response) => response.json())    .then((res) => console.log(res))    .catch((err) => console.log(err))    .finally(setLoading(false));  }

I don't know if the syntax I use with fetch is "good" and "optimize" for a login system, but I hope I was clear enough in my explanation.

Tanks

How to called async function in useEffect after submiting in react native?

$
0
0

I would like once the user click on the submit button for the whole "page" to reload and the useEffect function to be called. The current behavior is that when the user clicks the submit button, the useEffect function is not called at all. It is as if it does not reload directly after submission. I don't know if this is due to async and await. I give you the code :

useEffect() :

useEffect(() => {    console.log('test useEffect');    (async () => {      try {        const value = await AsyncStorage.getItem('authToken_Lust');        if(value !== null) {          const decodedValue = jwt_decode(value);          const current_time = Date.now() / 1000;          if(decodedValue.exp < current_time) {            setMessage('Vous n\'êtes plus connecté(e).')          } else {            setMessage('Vous êtes connecté(e)');          }        }      } catch(err) {        console.log(err);      }    })();  }, []);

The code of the function called after the user clicks submit :

const onSubmit = async () => {    setLoading(true)    await fetch('http://192.168.1.36:3000/api/users/login', {      method: 'POST',      headers: {        Accept: 'application/json','Content-Type': 'application/json'      },      body: JSON.stringify({        email: email,        password: password      })    })    .then((response) => response.json())    .then(async (res) => {      if(res.error) {        setMessage(res.error);      } else {        try {          await AsyncStorage.setItem('authToken_Lust', res.token);        } catch (err) {          console.log(err);        }      }    })    .catch((err) => console.log(err))    .finally(() => setLoading(false));  }

Tanks

When i try using nested navigators it doesn't work on web (Reactive Native)

$
0
0

I'm new to react native and started learning about nested navigators.I tried to have the drawer and the stack navigator at the same time, but when i try it only works when i see the project on mobile, on web it's all blank.I can see the page appearing for a millisecond before it vanishes whenever i make a change to the code and hit save.

I've already read the documentations about it and watched some videos but nothing works.

Here's a simplified code of my index.tsx:

const Drawer = createDrawerNavigator();const Home=()=>{    return(<NavigationContainer><Drawer.Navigator drawerContent={props => <CustomDrawerContent {...props}/>} initialRouteName="Main Menu"><Drawer.Screen name="Main Menu" component={StackMainMenu}/></Drawer.Navigator></NavigationContainer>    )}const Stack = createStackNavigator();const StackMainMenu = ()=>(<Stack.Navigator><Stack.Screen name="Main Menu" component={MainMenu}/></Stack.Navigator>);

It works perfectly when seeing it on my phone, i can see the top bar and i can slide the drawer menu, on web it shows only a white page.

I also get this warning when compiling: Attempted import error: 'shouldUseActivityState' is not exported from 'react-native-screens'. maybe it has something to do?

Aditional information if it helps:

I'm using expo.I type npm start to launch the code.Using google chrome for web testing and android for mobile.I'm using Linux Mint

How to pass props to StyleSheet in React Native using TypeScript?

$
0
0

I wanna create a custom button component that can pass props to the StyleSheet. At this project, the props I wanna send is the hexcode so the component can have different colors based on the color props that are passed to the component. So, I have written this

type Props = {  backgroundColor: string;  borderColor: string;};export const CustomButton = ({  backgroundColor,  borderColor,}: Props) => {  return (<TouchableOpacity      style={styles({ backgroundColor, borderColor }).container}></TouchableOpacity>  );const styles = ({ backgroundColor, borderColor }: Props) =>  StyleSheet.create({    container: {      backgroundColor: backgroundColor,      borderColor: borderColor,    },  });

The idea is to pass the props to the component, and then pass it to the styles on the Touchable component. But, this doesn't work. This always gives me this error on styles({ backgroundColor, borderColor}).container

Argument of type "{ backgroundColor, borderColor }" is not assignable to parameter of type "Props".

So, what went wrong? How am I supposed to pass the props to the StyleSheet?

react-native types file appears to not have the new AccessibilityInfo types?

$
0
0

I am using react-native 0.63 and I am using AccessibilityInfo.fetch() which is now deprecated. I am trying to update to AccessibilityInfo.isScreenReaderEnabled() however i am getting an issue with my typescriping that Property 'isScreenReaderEnabled' does not exist on type 'AccessibilityInfoStatic'. I went to the node_modules/@types/react-native/index.d.ts and indeed under AccessibilityInfoStatic there is no value isScreenReaderEnabled.

Has anyone solved this problem?

Thanks for your help.

Property 'Ripple' does not exist on type 'typeof TouchableNativeFeedback'.ts(2339)

$
0
0

I'm trying to create a button using TouchableNativeFeedback but I ran into an error. This is my code:

export const Button = ({props}: Props) => {  const [rippleColor, setRippleColor] = useState(primaryColor);  const [rippleOverflow, setRippleOverflow] = useState(true);  return (<TouchableNativeFeedback      onPress={onPress}      background={TouchableNativeFeedback.Ripple(rippleColor, rippleOverflow)}><View}>{children}</View></TouchableNativeFeedback> )}

With this code I got this error

Property 'Ripple' does not exist on type 'typeof TouchableNativeFeedback'.ts(2339)

Anyone knows what should I do? I've tried passing the rippleColor& rippleOverflow as props and sets the type on type Props = {} but it doesn't work either.


Cannot see FlatList inside Modal

$
0
0

Hi i've got a problem with seeing names added to list. Before using Modal everything works fine, but after I use it, after pressing "+" button, nothing happens. I mean I cannot see names in FlatList

///Main_file.tsximport { StatusBar } from 'expo-status-bar';import React, {useState} from 'react';import {   StyleSheet,   View,   Button,   FlatList} from 'react-native';import GoalItem from'./components/Goalitem';import GoalInput from './components/Goalinput';export default function App() {  const [courseGoals, setCourseGoals]  = useState<any>([]);  const [isAddMode, setIsAddMode] = useState(false);  function addGoalHandler(goalTitle: string):void  {    setCourseGoals([...courseGoals,{id: Math.random().toString(), value: goalTitle}]);  };  function removeGoalHandler(goalId:string):void  {    setCourseGoals((courseGoals: any[]) =>     {      return courseGoals.filter((goal:any) => goal.id !== goalId);    });  };  return (<View style = {styles.screen}><Button title="Turn on adding mode" onPress = {()=>setIsAddMode(true)}/><GoalInput  visible = {isAddMode} onAddGoal = {addGoalHandler} placeholder onChangeText style value/><FlatList         keyExtractor={(item, index) => item.id}        data ={courseGoals}         renderItem ={itemData => (<GoalItem           id = {itemData.item.id}           onDelete = {removeGoalHandler}           title = {itemData.item.value}           />        )}      /></View>   );}const styles = StyleSheet.create({  screen:{    padding:50,  }});

And the second file with goal input

import React, {useState} from 'react'import {View, TextInput, Button, StyleSheet, Modal} from 'react-native'type Props = {    value:any,    style: any,    onAddGoal: any,    placeholder: any,    onChangeText: any,    visible:boolean}const GoalInput = (props:Props) =>{    const [enteredGoal, setGoal] = useState<string>('');    const goalInputHandler = (enteredText:string) =>{        setGoal(enteredText);     };    return(<Modal visible={props.visible} animationType="slide"><View style = {styles.inputContainer}><TextInput                     placeholder="Dodaj przedmiot do listy zakupów"                     style={styles.input}                     onChangeText={goalInputHandler} //1.onChangeText pobiera wpisany text i wysyła do goalInputHandler                    value={enteredGoal}                /><Button title = '+' onPress = {props.onAddGoal.bind(this,enteredGoal)}/></View></Modal>    );};const styles = StyleSheet.create({    inputContainer:{        flexDirection: 'column',         justifyContent: 'flex-start',         alignItems: 'center'      },      input:{        width:'80%',         padding: 10,         borderColor: "black",         borderWidth: 1      }  });  export default GoalInput;

I'm doing everything like in course React Native - The Practical Guide by Maximilian Schwarzmüller but he's coding in js and i'm in ts.

React Native: Flip card animation doesn't work in functional component

$
0
0

I am new to React Native. I tried to create flip card animation and I was following a tutorial, and created the animation but it shows only one side of the card when the animation ends. I think the problem comes from my style but couldn't figure out how to fix this.

My current code is this.

const CardFlip = ({ navigation, route }: Props) => {  const animatedValue = new Animated.Value(0);  const [val, setVal] = useState(0);  const frontInterpolate = animatedValue.interpolate({    inputRange: [0, 180],    outputRange: ['0deg', '180deg'],  });  const backInterpolate = animatedValue.interpolate({    inputRange: [0, 180],    outputRange: ['180deg', '360deg'],  });  const frontAnimatedStyle = {    transform: [      { rotateY: frontInterpolate }    ]  };  const backAnimatedStyle = {    transform: [      { rotateY: backInterpolate }    ]  };  useEffect(() => {    animatedValue.addListener(({ value }) => {      setVal(value);    });  });  const flipCard = (): void => {    Animated.spring(animatedValue, {      toValue: val >= 90 ? 0 : 180,      friction: 8,      tension: 10,      useNativeDriver: true,    }).start();  };  return (<View style={styles.screen}><View style={styles.cardWrapper}><Animated.View style={[styles.card, frontAnimatedStyle]}><Text style={styles.text}>            Front</Text></Animated.View><Animated.View style={[styles.cardBack, backAnimatedStyle]}><Text style={styles.text}>            Back</Text></Animated.View>             </View><View style={styles.buttonWrapper}><TouchableOpacity          style={styles.flipCardButton}><Icon             name="visibility"            type="material"            color="#FFFFFF"            size={30}            onPress={() => flipCard()}          /></TouchableOpacity></View></View>  );};const styles = StyleSheet.create({  screen: {    height: '100%',    width: '100%',    top: 0,    left: 0,    backgroundColor: '#F7F3EC',  },  cardWrapper: {    alignItems: 'center',  },  card: {    position: 'absolute',    height: 480,    width: 320,    top: 40,    paddingTop: 45,    paddingHorizontal: 25,    backgroundColor: '#F9D6E2',    borderRadius: 7,    borderWidth: 0,    elevation: 6,    backfaceVisibility: 'hidden',  },  cardBack: {    position: 'absolute',    height: 480,    width: 320,    top: 40,    paddingTop: 45,    paddingHorizontal: 25,    backgroundColor: '#F9D6E2',    borderRadius: 7,    borderWidth: 0,    elevation: 6,    backfaceVisibility: 'hidden',  },  text: {    fontSize: 24,  },  buttonWrapper: {    position: 'absolute',    alignItems: 'center',    width: '100%',    height: 60,    bottom: 0,  },  flipCardButton: {    alignItems: 'center',    justifyContent: 'center',    height: 60,    width: 60,    position: 'absolute',    bottom: 10,    borderRadius: 100,    borderWidth: 0,    elevation: 6,    backgroundColor: '#EF5350',  }});

And the animation is like this.

enter image description here

How can I fix this?

Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component

$
0
0

So, i have this component SidebarMenu from the drawerContent of Drawer.Navigator

    const SidebarMenu: React.FC<SidebarMenuProps> = (props) => {      return (<View style={{ flex: 1 }}><DocenteMenu /><DrawerContentScrollView {...props}><View style={styles.itemContent}><MenuItem label="Home" icon="home" pageName="Home" {...props} /><MenuItem label="Chamada eletrônica" icon="edit" pageName="CallList" {...props} /><MenuItem label="Horário aula" icon="calendar" pageName="ClassSchedule" {...props} /><MenuItem label="Diário eletrônico" icon="book-open" pageName="ClassDiary" {...props} /><MenuItem label="Agendamento prova" icon="file-plus" pageName="TestSchedule" {...props} /><MenuItem label="Relação de alunos" icon="users" pageName="StudentsList" {...props} /><MenuItem label="Holerite" icon="file-text" pageName="Payslip" {...props} /></View></DrawerContentScrollView><View style={styles.logoutContent}><MenuItem label="Sair" icon="log-out" /></View></View>      );    }    export default SidebarMenu;

and I'm trying return a view from component DocenteMenu but its in that moment who returns a error. I alredy try to transform this function into "export default function" and return same error

interface TeacherProps {  COD_FUNCIONARIO: string,  NOME_FUNC: string;  DTA_NASC: Date;  CPF: string;  FOTO: string;}const DocenteMenu = () => {  const [user, setUser] = useState<TeacherProps | null>();  useEffect(function setUserProps() {    const {docente} = useAuth();    setUser(docente);  }, []);  return(<View style={styles.teacherInfo}><Image        style={styles.avatar}        source={{ uri: user?.FOTO }}      /><Text style={styles.teacherName}>{user?.NOME_FUNC}</Text><Text style={styles.teacherCode}>{user?.COD_FUNCIONARIO }</Text></View>  );}export default DocenteMenu;

React Native. How to get user local authentication whenever the app comes from the background?

$
0
0

Well, I can`t find anything like this on the web, so I am hoping someone can help me on this one.

I`m creating a bare react native android app, and I need to check for the user's Local Authentication whenever the app comes from the background.

I'm using Expo Authentication to handle the authentication, however, checking the app state with AppState from React Native is not useful, since every time the authentication screen (biometrics, facial recognition or even the PIN number) shows up on the screen the AppState will change from active to background, so it will require for an authentication again and again, because it will always come from the 'background'.

I'm not able to control it with a variable, since I don't have any identifier that could tell me the app came from expo Local Authentication screen, so I`m stuck on this "which came first, the chicken or the egg" problem.

Here is the part of the component that I`ve created to handle it so far:

    AppState.addEventListener('change', _handleAppStateChange);    return () => {      AppState.removeEventListener('change', _handleAppStateChange);    };  }, []);  const _handleAppStateChange = async (nextAppState: any) => {    if (      appState.current.match(/inactive|background/) &&      nextAppState === 'active'    ) {      clearTimeout(authenticationRequiredTimeout);      if (user && shouldAuthenticate) {        LocalAuthentication.hasHardwareAsync().then((hasHardware) => {          if (hasHardware) {            LocalAuthentication.isEnrolledAsync().then((isEnrolled) => {              if (isEnrolled) {                LocalAuthentication.authenticateAsync().then(                  (authentication) => {                    if (authentication.success !== true) {                      logout();                    }                    setShouldAuthenticate(false);                    console.log(authentication);                  },                );              }            });          }        });      }    } else {      let timeout = setTimeout(() => {        setShouldAuthenticate(true);      }, 5000);      setAuthenticationRequiredTimeout(timeout);    }    console.log(shouldAuthenticate);    appState.current = nextAppState;    console.log('AppState', appState);  };```Any help would be much appreciatted

How to use a TFLite model on a javascript program?

$
0
0

I have a program I'm working on that uses JavaScript (or typescript and react native, more specifically) to classify images taken by the camera or selected from the device's gallery. I have a TFLite model ready to use, but I'm not sure how to get those images to work with the model.

I think my biggest issue is I don't fully understand how the code I'm using interacts with the different modules I've been trying.

Here's what I have so far.

export default class CameraPage extends React.Component {  camera = null;    state = {        captures: [],        capturing: null,        hasCameraPermission: null,        cameraType: Camera.Constants.Type.back,        flashMode: Camera.Constants.FlashMode.off,    };    setFlashMode = (flashMode) => this.setState({ flashMode });    setCameraType = (cameraType) => this.setState({ cameraType });    handleCaptureIn = () => this.setState({ capturing: true });    handleCaptureOut = () => {        if (this.state.capturing)            this.camera.stopRecording();    };    handleShortCapture = async () => {        const photoData = await this.camera.takePictureAsync();        this.setState({ capturing: false, captures: [photoData, ...this.state.captures] })    };    handleLongCapture = async () => {        const videoData = await this.camera.recordAsync();        this.setState({ capturing: false, captures: [videoData, ...this.state.captures] });    };    async componentDidMount() {        const camera = await Permissions.askAsync(Permissions.CAMERA);        const audio = await Permissions.askAsync(Permissions.AUDIO_RECORDING);        const hasCameraPermission = (camera.status === 'granted'&& audio.status === 'granted');        this.setState({ hasCameraPermission });    };    render() {        const { hasCameraPermission, flashMode, cameraType, capturing, captures } = this.state;        if (hasCameraPermission === null) {            return <View />;        } else if (hasCameraPermission === false) {            return <Text>Access to camera has been denied.</Text>;        }        return (<React.Fragment><View><Camera                        type={cameraType}                        flashMode={flashMode}                        style={styles.preview}                        ref={camera => this.camera = camera}                    /></View>                {captures.length > 0 && <Gallery captures={captures}/>}<Toolbar                     capturing={capturing}                    flashMode={flashMode}                    cameraType={cameraType}                    setFlashMode={this.setFlashMode}                    setCameraType={this.setCameraType}                    onCaptureIn={this.handleCaptureIn}                    onCaptureOut={this.handleCaptureOut}                    onLongCapture={this.handleLongCapture}                    onShortCapture={this.handleShortCapture}                /></React.Fragment>        );    };}

My first issue is I need to know where the images are going and how to reference them. Second, how to use those images in a TFLite model. And third how to do the same thing pulling the images instead from the gallery.

After all that, I need to see about taking optimal images from a short video to use in the model, but I'll tackle that in another ask if I can't figure it out.

Thank you.

ReactElement type casting

$
0
0

This is more of a Typescript and React question but for full disclosure, I'll mention that I ended up here while trying to create a custom header using react-navigation.

I have a simple ImageButton (functional) component, which accepts the following props:

export interface ImageButtonProps extends TouchableOpacityProps {  transparent?: boolean;}

My custom header looks (roughly) like this:

export default function Header(props: StackHeaderProps) {   const options = props.scene.descriptor.options;   const HeaderRight = options.headerRight as (() => ReactElement<ImageButtonProps>);   return (<HeaderRight transparent={true}/>); // <-- Typescript complains here}

It's safe to assume that options.headerRight will always return an ImageButton, which in fact renders just fine. The only issue is that the property transparent is always undefined and also Typescript throws the following error:

TS2322: Type '{ transparent: boolean; }' is not assignable to type 'IntrinsicAttributes'.   Property 'transparent' does not exist on type 'IntrinsicAttributes'.

So my question is, how can I properly cast a ReactElement to my custom component, ImageButton and its props?

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!


Does setState or dispatch (useReducer hook) make component re-render before calling next lines?

$
0
0

I realize a problem when using useState and useReducer hook that any lines of code after the update state function (setState, dispatch) will be called in the next re-rendering (with its previous state before update). It means that update state function causes re-rendering immediately and not waiting the whole function executed.

const [aaa, setAAA] = useState<boolean>(false);const updateMyBiddingList = async (atDate?: string) => {    try {      console.log('step 0');      const result = await getBiddingCartFromService(atDate ? atDate : myBiddingListState.myBiddingList[0].updatedAt);      if (result.responseCode.toString().startsWith('2')) {        setState(true);        console.log('step 1');      }      console.log('step 2 ', aaa);    }    catch (err) {      if (timeOut.current) clearTimeout(timeOut.current);      timeOut.current = setTimeout(() => updateMyBiddingList(), TIMEOUT);    }  }console.log('Component is re-rendering... ', aaa);return ...

The above codes will log in the following order:

  • step 0
  • Component is re-rendering... true
  • step 1
  • step 2 true

Does anyone explain the workflow of update state hook for me? Thank in advance.

React Navigation route.params typescript

$
0
0

I'm creating a Expo managed React Native app with TypeScript and having some problems with React Navigation and TypeScript.

I want to specify the icon for the Bottom Tab Navigator on the Tab.Screen component.

This code works but complains because route.params could be undefined (line 10).

Property 'icon' does not exist on type 'object'

Can I make the icon prop required on initialParams?

I have looked in the documentation without any luck.

const App: React.FC<{}> = () => {  return (<SafeAreaView style={styles.container}><NavigationContainer><Tab.Navigator          screenOptions={({ route }) => ({            tabBarIcon: ({ size, color }) => (<MaterialIcons                size={size}/* ===> */      name={route.params.icon}                color={color}              />            ),          })}><Tab.Screen            name="EventListView"            initialParams={{ icon: 'view-agenda' }}            component={EventListScreen}          /><Tab.Screen            name="CreateEvent"            initialParams={{ icon: 'public' }}            component={SettingsScreen}          /></Tab.Navigator></NavigationContainer></SafeAreaView>  )}

Type '(text: string) => void' is not assignable to type '() => void'

$
0
0

I'm creating a custom component for TextInput. But I've got a problem when I try to pass a function prop to the custom component. This is the code

// Screen.tsxexport const RegisterScreen = ({props}: Props) => {  const [text, setText] = useState("");  const onChangeInputText = (text: string) => setText(text);  return (<View><CustomInput onChangeText={onChangeInputText} text={text} /></View>// CustomTextInput.tsxtype Props = {  onChangeText: () => void;  text?: string;};export const CustomInput = ({ onChangeText, text }: Props) => {  return (<TextInput      style={styles.container}      onChangeText={onChangeText}      value={text}      placeholder="Type here"    />  );};

With this code, I got this error

Type '(text: string) => void' is not assignable to type '() => void'

I think I know what causes this (it's probably on the type declaration?) but since this is actually my first time trying TypeScript, I can't really figure out how to solve this. Tried googling about this first but I didn't find any error similar to mine.

Check with TS that both optional params either passed or undefined

$
0
0

I'm writing an app with React native and Typescript and I have a question.

Let's image we have a simple component with three properties, one required and two optional:

interface Props {  requiredProp: string;  optionalPropA: boolean;  optionalPropB: Function;}

In my app logic either both optional properties have to be passed or none of them and I'm wondering how can I check that with TS?

I can think of only two ways how I can achieve that:

  1. Without using TS just simply check my condition with if somewhere before return
  2. Combine two optional properties into one. Make an object with two keys (one for each property) and make a TS type that will make sure that either both or none of them exists

Some examples:

// Should be good because all params were passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropA={true}  optionalPropB={() => {}}/>
// Should be good because only required param was passed<SimpleComponent  requiredProp={'Hello world'}/>
// Should complain that optionalPropB wasn't passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropA={true}/>
// Should complain that optionalPropA wasn't passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropB={() => {}}/>

How do I build apk from edited source?

$
0
0

I just fixed some-how problem with expo start, but now I want to build the app from this source code using gradlew assembleRelease, after entering command I get this error :

:ReactNative:Unexpected empty result of running '[node, C:\Users\Mathew\Desktop\wallet-master\node_modules\@react-native-community\cli\build\bin.js, config]' command.:ReactNative:Running '[node, C:\Users\Mathew\Desktop\wallet-master\node_modules\@react-native-community\cli\build\bin.js, config]' command failed.FAILURE: Build failed with an exception.* Where:Script 'C:\Users\Mathew\Desktop\wallet-master\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 195* What went wrong:A problem occurred evaluating script.> internal/modules/cjs/loader.js:1032  throw err;  ^Error: Cannot find module 'C:\Users\Mathew\Desktop\wallet-master\node_modules\@react-native-community\cli\build\bin.js'    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1029:15)    at Function.Module._load (internal/modules/cjs/loader.js:898:27)    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)    at internal/main/run_main_module.js:17:47 {  code: 'MODULE_NOT_FOUND',  requireStack: []}```I"m out of ideas what is wrong and what module is missing (not found ).
Viewing all 6287 articles
Browse latest View live


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