Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all 6218 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?


Rollup is not adding react-native components to bundle imports

$
0
0

I try to build a react-native/-web library to share components between two projects,but rollup is not recognising the react-native components when they are used in a component and response with this error:

(!) Unused external importsView,Text,TouchableOpacity,ActivityIndicator,TextInput,Picker,FlatList,StatusBar imported from external module 'react-native' but never useddefault imported from external module 'react-native-easy-content-loader' but never usedSvg,G,Path,default,Polygon,Polyline,Rect,Circle,Defs,Mask,Use imported from external module 'react-native-svg' but never usedTextInputMask imported from external module 'react-native-masked-text' but never used

It also means that it is not importing them in the bundle files:

import { StyleSheet, Platform, UIManager, LayoutAnimation, Dimensions, PixelRatio, Animated, PanResponder, Image } from 'react-native';

This is my rollup config:

import alias from '@rollup/plugin-alias';import jsx from 'acorn-jsx';import path from 'path';import typescript from 'rollup-plugin-typescript2';import pkg from './package.json';export default {  input: 'src/index.ts',  output: [    {      file: pkg.main,      format: 'cjs',      sourcemap: true,    },    {      file: pkg.module,      format: 'esm',      sourcemap: true,    },  ],  external: [    ...Object.keys(pkg.dependencies || {}),    ...Object.keys(pkg.peerDependencies || {}),  ],  acornInjectPlugins: [jsx()],  plugins: [    alias({      entries: {        components: path.resolve(__dirname, './src/components'),        context: path.resolve(__dirname, './src/context'),        gql: path.resolve(__dirname, './src/gql'),        types: path.resolve(__dirname, './src/types'),        utils: path.resolve(__dirname, './src/utils'),      },    }),    typescript({      typescript: require('ttypescript'),      tsconfigDefaults: {        compilerOptions: {          plugins: [            {transform: 'typescript-transform-paths'},            {transform: 'typescript-transform-paths', afterDeclarations: true},          ],        },      },    }),  ],};

and my tsconfig.json:

{"compilerOptions": {"allowSyntheticDefaultImports": true,"baseUrl": ".","declaration": true,"declarationDir": "dist","jsx": "react-native","module": "esnext","moduleResolution": "node","sourceMap": true,"target": "es5","paths": {"components/*": ["src/components/*"      ],"context/*": ["src/context/*"      ],"gql/*": ["src/gql/*"      ],"types/*": ["src/types/*"      ],"utils/*": ["src/utils/*"      ],    },  },"include": ["src/**/*"  ],"exclude": ["node_modules","../../node_modules","dist","src/**/*.stories.*","src/**/*.test.*"  ]}

I'm not sure if I do something wrong in my config or if this is a bug with the rollup tree shaking.Hope someone can help.Thanks.

Extending react-native-paper components in TypeScript

$
0
0

I'm struggling to extend react-native-paper components correctly. What am I doing wrong or how to do it correctly? Actually I'm not totally new to Typescript, but I always struggled with this one :(

// TextInput.tsx

import React from "react";import { TextInput as PaperTextInput } from "react-native-paper";import { TextInputProps } from "react-native-paper/lib/typescript/src/components/TextInput/TextInput";interface MyTextInputProps extends TextInputProps {}const MyTextInput: React.FC<MyTextInputProps> = (props) => {  return <PaperTextInput {...props} />;};export default MyTextInput;

// Usage:

<TextInput mode="outlined" style={styles.input} label="Email" />

And I get this error:Property 'theme' is missing in type '{ mode: "outlined"; style: { alignSelf: "stretch"; }; label: string; }' but required in type 'MyTextInputProps'

Thank you for understanding what am I doing wrong.

Arrow function returning component with TypeScript in React Native

$
0
0

I'm trying to build an app in React Native using Typescript, but i'm facing some problems with some of the typescript rules.I just copy and paste an UI Kitten component code and it returns a TypeError

const PersonIcon = (props: any) => ( <Icon {...props} /> );

const BellIcon = (props: any) => ( <Icon {...props} name='bell-outline'/> );

const EmailIcon = (props: any) => ( <Icon {...props} name='email-outline'/> );

And then using it in the component:

const [selectedIndex, setSelectedIndex] = useState(0);return(<TabBar        selectedIndex={selectedIndex}        onSelect={index => setSelectedIndex(index)}><Tab icon={EmailIcon} title='USERS'/><Tab icon={BellIcon} title='ORDERS'/><Tab icon={EmailIcon} title='TRANSACTIONS'/></TabBar>)

And with that I can't procceed because I can't find something like a tutorial which teaches how to use TypeScript in React Native. Could someone help me? I know this is a newbie error, but I really can't find the solution

The error

items passed into flatList are undefined

$
0
0

I run a graphql query and get back some data.

let DATA;  const { error, data, refetch } = useUsersQuery({    variables: {      where: { id: 1 },    },    onCompleted: () => {      console.log('friendsData', data);      DATA = data.users.nodes[0].userRelations.map(        (item: {          relatedUser: {            firstName: string;            id: number;            rating: number;            vehicles: Array<Vehicle>;            userRelations: Array<User>;          };        }) => ({          id: item.relatedUser.id,          imageUrl: defaultUrl,          name: item.relatedUser.firstName,          rating: item.relatedUser.rating,          vehicles: item.relatedUser.vehicles,          numberOfFriends: item.relatedUser.userRelations.length,        }),      );      console.log('info aabout friends', DATA)    },    onError: () => {      DATA = [        {          id: '1',          imageUrl: defaultUrl,          name: 'Friend',        },      ];    }  }  ,  );

The query is successful and I know that because when I check with console.log('info aabout friends', DATA), I get something like

Array (1){id: 2, imageUrl: "https://i.pinimg.com/originals/19/19/df/1919dfda3b3f19392ddb9205b4e1331c.png", name: "Alice", rating: 2, vehicles: [{numberPlate: "OL-AL-1336", id: 2, __typename: "Vehicle"}], …}

Now I am passing it like this to my flat list:

<FlatList          data={DATA}          horizontal={true}          renderItem={({ item }) => (<WhitelistItem              title={item.name}              face={item.imageUrl}              firstName={item.name}              rating={item.rating}              numberOfFriends={item.numberOfFriends}              vehicles={item.vehicles}            />          )}          keyExtractor={(item) => item.id}        />

However, when I console log and check from my WhitelistItem component, the values for example (firstName) are all undefined and hence nothing is rendered.

type WhitelistItemProps = {  title: string;  face: string;  firstName?: string;  rating?: number;  // numberPlate?: string;  numberOfFriends?: number;  vehicles?: Array<Vehicle>;};export const WhitelistItem: React.FunctionComponent<WhitelistItemProps> = ({  title,  face,  firstName,  rating,  numberOfFriends,  vehicles,}) => {  console.log('firstname', firstName);  const navigation = useNavigation();  return (<TouchableOpacity      activeOpacity={0.8}><View style={styles.item}><Thumbnail small source={{ uri: face }} style={styles.thumbnail} /><Text numberOfLines={1}>          {title}</Text></View></TouchableOpacity>  );};

This was working previously but when I changed the query structure, it stopped working.

It works like this but not with onCompleted etc:

    const { error, data, refetch } = useUsersQuery({    variables: {      where: { id: 1 },    }});  let DATA;  if (data) {    DATA = data.users.nodes[0].userRelations.map(      (item: {        relatedUser: {          firstName: string;          id: number;          rating: number;          vehicles: Array<Vehicle>;          userRelations: Array<User>;        };      }) => ({        id: item.relatedUser.id,        imageUrl: defaultUrl,        name: item.relatedUser.firstName,        rating: item.relatedUser.rating,        vehicles: item.relatedUser.vehicles,        numberOfFriends: item.relatedUser.userRelations.length,      }),    );  } else {    DATA = [      {        id: '1',        imageUrl: defaultUrl,        name: 'Friend',        vehicles: [],      },      {        id: '2',        imageUrl: defaultUrl,        name: 'Friend',        vehicles: [],      },      {        id: '3',        imageUrl: defaultUrl,        name: 'Friend',        vehicles: [],      },    ];  }

React-native picker with hooks typescript

$
0
0

I started studying react a short time ago and I did a project with select taking values ​​from an external api, it worked ok. When I went to react-native, to carry out the same project, I ended up getting stuck in the use of the picker, actually, with some control of the typescript.

Here is my code:

interface IBGEUFResponse {  sigla: string;}interface IBGECityResponse {  nome: string;}const Home = () => {  const [ufs, setUfs] = useState<string[]>([]);  const [cities, setCities] = useState<string[]>([]);  const [selectedUf, setSelectedUf] = useState('');  const [selectedCity, setSelectedCity] = useState('');

Here with some useEffect and control:

useEffect(() => {    axios.get<IBGEUFResponse[]>('https://servicodados.ibge.gov.br/api/v1/localidades/estados?orderBy=nome')    .then(response => {      const ufInitials = response.data.map(uf => uf.sigla);      setUfs(ufInitials);    });  }, []);  useEffect(() => {    if(selectedUf === '') {      return;    }    axios.get<IBGECityResponse[]>(`https://servicodados.ibge.gov.br/api/v1/localidades/estados/${selectedUf}/municipios`)    .then(response => {      const cityNames = response.data.map(city => city.nome);      setCities(cityNames);    });  }, [selectedUf]);

and finally the picker:

<Picker            style={styles.input}            selectedValue={selectedUf}            onValueChange={newUf => setSelectedUf(newUf)}>            {ufs.map(uf => {           return (<Picker.Item key={uf} label={uf} value={uf}            />           );})}

So setSelectedUf(newUf) gets a (TS:2345) error in (newUf) and i can't see how to make it's work.

Sorry guys, but I spent a couple of days looking for solutions on the internet, adapting solutions for similar errors and I couldn't solve it.

Type is missing the following properties from type in TypeScript of React-Native app

$
0
0

I have installed https://github.com/react-native-community/react-native-modal library and I need to make a wrapper Modal class. The first initialize Interface. It extends from a few interfaces from react-native and react-native-modal libraries. It means I can use all properties from both of them:

import { ModalProps } from 'react-native';import { ReactNativeModal, ModalProps as ModalRNProps } from 'react-native-modal';export interface IModalProps extends Omit<ModalProps, 'onShow'>, ModalRNProps {  showCloseButton?: boolean;  showDoneBar?: boolean;}export class ModalNew extends React.Component<IModalProps> {  public render() {    const {      style,      children,      showCloseButton,      showDoneBar,      animationType,      onRequestClose,      ...props    } = this.props;    return (<ReactNativeModal       isVisible={this.props.isVisible}       onModalWillHide={onRequestClose}       animationIn={'slideInUp'}       animationOut={'slideOutDown'}       animationOutTiming={600}       useNativeDriver={true}       backdropOpacity={0.6}       backdropColor={theme.black}       style={style}       {...props}>       {children}</ReactNativeModal>    );  }}

But after when I use it in other component:

import React, { Component } from 'react';import { ModalNew } from './ModalNew';export class FooterHiddenPanel extends Component {  const props = this.props;  render() {    return (<ModalNew isVisible={props.isActive} onRequestClose={props.onRequestClose}><Text>This is </Text></ModalNew>    );  }}

I get this error:

enter image description here

It means I have to use all properties from both PropsTypes that I has extended my interface. But I don't need all of them. If I extend my class from a few interfaces I must implement all properties? Can you tell me please how can I get rid from this error?

Property 'HEIGHT' does not exist on type 'NamedExoticComponent'

$
0
0

I am trying to use Header.HEIGHT from react-navigation-stack for the react-navigation header height calculation but as soon as I upgraded my react-native version from 0.59 to 0.61, I am getting some linting issues on typescript

issue: Property 'HEIGHT' does not exist on type 'NamedExoticComponent'issue in code: const headerHeight = Header.HEIGHT

Not sure how to fix it.


Need to click twice in KeyboardAvoidingView even when keyboardshouldpersisttaps is always

$
0
0

I am using a KeyboardAvoidingView to move a button up with the keyboard, within that I have a scrollview which keybordShouldPersistTaps is set to always, within the scrollview, I am using a Formik form. I still have to double click a button twice in order to get the keyboard to dismiss and submit my data. I have always tried to manually dismiss/handle the keyboard on the scrollview with no luck, Any other approaches I should try?

<KeyboardAvoidingView style={{ flex: 1 }} behavior={'padding'}><ScrollView contentContainerStyle={{ flexGrow: 1 }} keyboardShouldPersistTaps={'always'}><Formik            initialValues={this.state}            validationSchema={this.schema}            onSubmit={(values, actions) => {                            actions.setSubmitting(false);            }}            render={({ handleBlur, handleChange, handleSubmit, values, isValid }) => {              return (<View style={onboardingStyles.inputContainer}><View><Text theme={theme} style={onboardingStyles.headerText}>                      {i18n.t('phone_verify')}</Text><TextInput                      activeHighlight                      value={RizeCore.util.formatPhoneDOM(values.phone)}                      onChangeText={(val: string) => {                        const phone = RizeCore.util.parseOutDigits(val, 10);                        return handleChange('phone')(phone);                      }}                      onBlur={() => handleBlur('phone')}                      label={i18n.t('phone_number')}                      style={onboardingStyles.input}                      labelStyle={{ color: 'white' }}                      keyboardType={Platform.OS === 'web' ? 'default' : 'number-pad'}                      returnKeyType="done"                    /></View><BottomFixedCTA                    ctaLabel={i18n.t('phone_send_code')}                    loading={smsCodeIsBusy}                    disabled={!isValid}                    onPress={handleSubmit as undefined}                    onBackPress={this._navSignUp}                  /></View>              );            }}          /></ScrollView></KeyboardAvoidingView>

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components)

$
0
0

I'm working on my react native project where I have a map screen in which the user can select their location.

The problem I'm facing is that I keep getting that error pointing to that particular screen, however I have a default export and I couldn't find any syntax error. I'm using TypeScript. Here's the code:

import * as React from "react";import { MapView } from "expo";import { View, StyleSheet, Dimensions } from "react-native";import PrimaryText from "../assets/constants/PrimaryText";import Loader from "../components/Loader";import * as Location from "expo-location";export default function MapSelectLocation({ route, navigation }: any) {  const [location, setLocation]: [null | string | any, any] = React.useState(    null  );  const [errorMsg, setErrorMsg]: [null | string | any, any] = React.useState(    null  );  React.useEffect(() => {    (async () => {      let { status } = await Location.requestPermissionsAsync();      if (status !== "granted") {        setErrorMsg("Permission to access location was denied");      }      let location = await Location.getCurrentPositionAsync({});      setLocation(location);    })();  });  if (errorMsg) {    return (<View><PrimaryText>          Por favor, habilitá la ubicación en tu celular.</PrimaryText></View>    );  }  if (location) {    let userLatitude = location.coords.latitude;    let userLongitude = location.coords.longitude;    return (<MapView        style={styles.mapStyle}        initialRegion={{          latitude: userLatitude,          longitude: userLongitude,          latitudeDelta: 1,          longitudeDelta: 1,        }}></MapView>    );  }  return <Loader />;}const styles = StyleSheet.create({  mapStyle: {    width: Dimensions.get("window").width,    height: Dimensions.get("window").height,  },});

A summary of the functionality: The component gets the user location and displays as the initialRegion. That's it for now.

pass data into component with 'let' keyword

$
0
0

I am trying to pass some data into my FlatList component after running a graphql query. If I hard-code data using const DATAit works. However, if I define two cases (successful query and unsuccessful query) and use let DATA, the variables aren't passed into the FlatList properly and they are always undefined inside FlatList component.

How can I fix this? How can I ensure that DATA is passed into the FlatListonly after the query has been run?

For example, hard coded data like this works:

const DATA = [  {    id: '1',    imageUrl: defaultUrl,    name: 'Friend',    vehicles: [],    rating: 1,    numberOfFriends: 3,  }];

But this doesn't (query works fine though):

let DATA; const { data, error } = useGetMyProfileQuery({    onCompleted: () => {      console.log('frineds', data.me.friends)      DATA = data.me.friends.map(        (item: {            firstName: string;            id: number;            rating: number;            vehicles: Array<Vehicle>;            friends: Array<User>;        }) => ({          id: item.id,          imageUrl: defaultUrl,          name: item.firstName,          rating: item.rating,          //vehicles: item.vehicles,          vehicles: [],          numberOfFriends: item.friends.length,        }),      );    },    onError: ()=> {          DATA = [            {              id: '1',              imageUrl: defaultUrl,              name: 'Friend',              vehicles: [],              rating: 1,              numberOfFriends: 3,            }        }  });

FlatList:

<FlatList          showsHorizontalScrollIndicator={false}          data={DATA}          horizontal={true}          //scrollEnabled          renderItem={({ item }) => (<WhitelistItem              title={item.name}              face={item.imageUrl}              firstName={item.name}              rating={item.rating}              numberOfFriends={item.numberOfFriends}              vehicles={item.vehicles}            />          )}          keyExtractor={(item) => item.id}        />

Edit:

I know about setStates but does this guarantee that every time the query re-runs, the data will be updated? Or do I necessarily have to use useEffect etc? In the past when I have used useStates, the data was often not updated automatically and kept giving old data so I was looking for an alternative way

Array types for useState

$
0
0

I have two cases in which I use setState to set an array of objects. Looks like this:

  const [friendList, setFriendList] = useState<any>();  const _onCompleted = (data: any) => {    let DATA = data.me.friends.map(      (item: {          firstName: string;          id: number;          rating: number;          vehicles: Array<Vehicle>;          friends: Array<User>;      }) => ({        id: item.id,        imageUrl: defaultUrl,        name: item.firstName,        rating: item.rating,        vehicles: [],        numberOfFriends: item.friends.length,      }),    );    setFriendList(DATA);  };

In case on onComplete, data looks like this:

DATAArray (3)0 {id: 1, imageUrl: "https://", name: "Bob", rating: 1, vehicles: [], …}1 {id: 3, imageUrl: "https://", name: "Rhena", rating: 3, vehicles: [], …}2 {id: 4, imageUrl: "https://", name: "Jack", rating: 4, vehicles: [], …}

Currently, I am using <any>, which works. However, I do not want to use any. I tried creating custom types:

type Friend = {  id: number,  imageUrl: string,  name: string,  rating?: number,  //vehicles: item.vehicles,  vehicles?: any,  numberOfFriends?: number,};type FriendList = {  friendList: Array<Friend>;};

but when I use it like this useState<FriendList>();, I get an error on setFriendList(DATA); from onError that Argument of type '{ id: string; imageUrl: string; name: string; }[]' is not assignable to parameter of type 'SetStateAction<FriendList | undefined>'.

Why is this so? The remaining fields in my Friend type are option so why do I get this error?

I also tried using useState<Array<Friend>>(); and useState([])but I get the same error.

Async Await API call inside componentDidMount() is suddenly failing/exceeding timeout? React-Native. Redux. Typescript

$
0
0

Async call inside componentDidMount is exceeding timeout and failing.

The api call itself is not using redux, but the data retrieved is.

Is this an instance where I would need to use Redux Thunk?How would Thunk be applied to the initial get call?

Can't seem to get passed the initial await call.

Component.tsx

 async componentDidMount() {    const { resetItems, loadItems } = this.props;    try {      const stuff: Stuff[] | null = await stuffService.getItems();      if (stuff && stuff.length > 0) {        loadItems(stuff);      } else {        resetItems();      }    } catch {}  }

stuffService.tsx

function getItems(): Promise<Stuff[] | null> {  return request({    url: "Items",    method: "GET",  });}

index.ts

export function loadItems(stuff: Stuff[]): ActionTypes {  return {    type: "LOAD_ITEMS",    stuff,  };}export function resetThings(): ActionTypes {  return {    type: "RESET_ITEMS",  };}

Things I've tried:Moving the call outside of componentDidMount.Using other life cycle methods.Using Thunk on the loadItems();

export function loadItemsAsync(stuff: Stuff[]) {  return (dispatch) => {    setTimeout(() => {      dispatch(loadItems(stuff));    }, 9000);  };}

render FlatList only when data is present

$
0
0

I run a graphql query and depending on the data, render a flatList.

  const { data, error } = useGetMyProfileQuery({    //onCompleted: _onCompleted,    onError: _onGetMyProfileQueryError,  });....return (<SafeAreaView style={styles.safeView}><Container style={styles.container}><View style={styles.listHolder}><FlatList            data={data ? data.me.friends : null}            horizontal={false}            renderItem={({ item }) => (<Friend                friend={item}                onDeleteFriend={onDeleteFriend}                originatorId={data ? data.me.id : null}              />            )}            keyExtractor={(data: any) => '3'}            ListEmptyComponent={renderEmptyContainer()}          /></View></Container></SafeAreaView>  );};

However, currently, I have to use ternary operators for checks like data? data.me.friends: null in the FlatList to avoid Typescript errors. If the query fails, and the data is null, It disturbs the whole performance and I will have to use multiple if-else within the whitelist item component too.

So I am looking for the best way such that data is passed into the Flatlist only when the mutation is successful. I could use onCompleted for that but I am not sure how to organize it such that no flat list is displayed from the main return when there's an error.

Also, currently, I am using the same key for all elements of the list but it shouldn't be like that obviously

React native text input blur/focus issue

$
0
0

Facing a weird issue on react native when having 2 text inputs. When pressing on central area of onfocused text input, the focus changes correctly, however, when i press on the area that covers ~30-50px from the left of text input, the focused text input gets unfocused and then focuses again.The issue seems to be same as here: Input text react native cannot get focus, however no solution was found on that question.any ideas on what can cause this problem and how to fix it?


Making a drawer navigator for app with multiply files

$
0
0

I have the following error:"Another navigator is already registered for this container.You likely have multiple navigators under a single "NavigationContainer" or "Screen" ".

But as my app is a little specific, i couldn't find anything that really helped, i'm using typescript and i could only find examples on youtube by people using javascript. This is my code:

Main App.tsx:

const Stack = createStackNavigator();

const Drawer = createDrawerNavigator();

export default function App() {

return (

<NavigationContainer><Stack.Navigator   initialRouteName="Login"  screenOptions={{headerShown: false}}><Stack.Screen      name="Home"      component={Home}    /><Stack.Screen      name="Login"      component={Login}    /></Stack.Navigator><Drawer.Navigator   initialRouteName="Home"><Drawer.Screen       name="Home"       component={Home}     /><Drawer.Screen       name="Profile"       component={ProfileScreen}    /></Drawer.Navigator></NavigationContainer>

);

}

Home.tsx (this is where my drawer should be)

export default function Home({ navigation }) {

return(<KeyboardAvoidingView>            <View style={styles.container}><Header                placement="left"                centerComponent={{ text: 'i B l o c k',                 style: { color: '#fff', fontWeight: 'bold', fontSize: 20 } }}                rightComponent={{                     icon: 'menu',                     color: '#fff',                    onPress: ()=> navigation.openDrawer()                }}                containerStyle={{                    marginTop: -25,                    backgroundColor: '#87C8E1',                    justifyContent: 'space-around',                  }}            /><Image                style={styles.quadra}                source = {require('../../assets/quadra.png')}            /></View></KeyboardAvoidingView>)

}

and finally my ProfileScreen.tsx

export default function ProfileScreen({ navigation }) {

return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Button onPress={() => navigation.goBack()} title="Go back home" /></View>);

}

I'm new to React-Native, so i really don't realize what i'm doing wrong.

react native testing library, async tests passing but receiving state updates need to be wrapped in act

$
0
0

hey all I have working tests and I know it wants me to wrap my render in an act but if I do that I get a warning stating it can't find root. yet if I then instead change it to create i can't use my getbyTestId method.

`it('should not render image', async () => {        // Arrange        // needs to be used to support async mounting methods like useeffect/componentdidmount        jest.useFakeTimers();        const testComment = {            text: 'placeholder'        } as WorkItemComment;        await act(async () => {            AsyncStorage.setItem('authMethod', 'msa')        });        const placeholderComment: WorkItemComment = testComment;        const placeholderImage: string = 'image';        // Act        const { queryByTestId } = render(<CommentList workItemComments={[placeholderComment]} profilePicture={[placeholderImage]} />);        // Assert        await wait(() => {            expect(queryByTestId('image')).toBeNull();        })    });`

actual component its rendering and where believe this error is stemming from.

`const fetch = async () => {    const authMethod = await AsyncStorage.getItem('authMethod');    setAuthMethod(authMethod!)  };  useEffect(() => {    fetch();  }, [props.workItemComments]);`

my actual error message is as followsconsole.error node_modules/react-native/Libraries/LogBox/LogBox.js:33Warning: An update to CommentList inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):act(() => {  /* fire events that update state */});/* assert on the output */This ensures that you're testing the behavior the user would see in the browser    in CommentList    in View (created by View)    in View (created by AppContainer)    in View (created by View)    in View (created by AppContainer)    in AppContainer (at src/index.js:26)

How to view console.log() of webpage running inside React Native WebView?

$
0
0

In my React Native code, I'm try to call my webpage inside WebView component. In that webpage I'm passing some data using window.postMessage() method from injectedJavascript attribute of React Native WebView. Based upon the data that I've passed to my web page, I'm displaying some console.log() on that page. So, my requirement is to capture those console logs from my webpage inside WebView component and display it in my React Native Code.

Below is my WebView Code:

<WebView  source={{      uri: 'https://www.example.com/',  }}  javaScriptEnabled={true}  injectedJavaScript={`window.postMessage({...}, '*')`}  onMessage={(event) => {      const { data } = event.nativeEvent;      console.log('MESSAGE >>>>'+ JSON.stringify(data));  }}/>

In short, whatever is print in the console of my webpage, I want to print that in my React Native's console, so that I can able to debug my webpage from WebView component by passing the data using window.postMessage().

TS2322 - false | Element is not assignable to type ReactElement. Error does not consistently appear in app?

$
0
0

I understand what the error is saying and I have been able to fix it, but I was hoping someone could provide some clarification on why it's happening now and why it isn't happening in other areas of my app, as well as why a function and a ternary with essentially the same type signature produce different results.

I wanted to display a basic error message in the following style:

{!!error.message && (<Text>{error.message}</Text>)}

But it gives the error mentioned in the title. I know false is handled by React and won't render anything, but knowing null is the preferred way of telling React not to render something I converted the above into a component. This makes the error go away:

const Error = () => {  if (!error.message) return null;  return <Text>{error.message}</Text>;}

Out of curiosity, I tried the same thing with a ternary which should have the same signature:

{error.message ? <Text>{error.message}</Text> : null}

However this produces a very similar error to the one in the title, except it complain about null instead.

Knowing all 3 bits of code are valid React, and 2/3 being virtually identical, why is only one accepted by the TS compiler?

To further confuse things, I have the below in another part of my app and TS has no issue with it:

{!loaded && (<RootStack.Screen name={SCREENS.SPLASH} component={Splash} />)}{loaded && !userAuth.authenticated && (<><RootStack.Screen name={SCREENS.SIGN_UP} component={SignUp} /><RootStack.Screen name={SCREENS.SIGN_IN} component={SignIn} /></>)}{loaded && userAuth.authenticated && (<RootStack.Screen name={SCREENS.TABS} component={Tabs} />)}

Nested Flatlist item toggle background colour when clicked on option button YES/NO/NA [closed]

$
0
0

I am trying to toggle a dynamic background color for a button in a nested Flatlist. I am able to change color but it changes all the element in the list.

I want to change the color of the questions based on the color that is provided in the array you can check out the full code in the snack below.

Snack URL - https://snack.expo.io/@jerrypatels/bossy-bagelRun the snack into phone to get more clarity enter image description here

JSON data for Loops

[  {    title: 'Q1',    data: [      {        Q: 'Question 1',        length: 2,        width: 38,        options: [          {id: 1, value: 'Yes', color: '#40AB35'},          {id: 2, value: 'No', color: '#C6280F'},        ],      },      {        Q:'Question 2',        length: 3,        width: 30,        options: [          {id: 1, value: 'Yes', color: '#40AB35'},          {id: 2, value: 'No', color: '#C6280F'},          {id: 3, value: 'NA', color: '#808289'},        ],      },      {        Q:'Question 3',        length: 2,        width: 38,        options: [          {id: 1, value: 'Yes', color: '#40AB35'},          {id: 2, value: 'No', color: '#C6280F'},        ],      },    ],  },]

React native code for displaying to front end

<FlatList        data={Alongside}        keyExtractor={(item, index) => ''+ index}        renderItem={({item}) => (<><View style={styles.buttonContainer}><View                style={{                  borderRadius: 2,                  borderBottomWidth: 1,                }}><TouchableOpacity                  style={styles.qtitle}                  onPress={() => GetStores()}><Text style={[styles.title, {width: width - 80}]}>                    {item.title}</Text></TouchableOpacity></View><FlatList                data={item.data}                keyExtractor={(item, index) => '2'+ index}                renderItem={({item, index}: any) => (<View style={{padding: 10}}><Text style={[styles.text, {padding: 10}]}>                      {item.Q}</Text><View style={styles.btnP}>                      {item.options.map((list: any, ind: any) => {                        return (<TouchableOpacity                            style={[                              styles.btn2,                              {                                width: width / item.length - item.width,                                backgroundColor:                                  checked === list.id //Condition for changing bg color                                    ? list.color                                    : '#F4F6FC',                              },                            ]}                            onPress={() => {                              //                              setChecked(list.id);                            }}><Text                              style={[                                Style.normalText,                                {textAlign: 'center'},                              ]}>                              {list.value}</Text></TouchableOpacity>                        );                      })}</View></View>                )}              />
Viewing all 6218 articles
Browse latest View live


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