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

Is there a significant difference between React-Native useEffect [] and a custom function inside iOS didFinishLaunchingWithOptions?

$
0
0

I am building a React-Native SDK library based on Swift/Kotlin modules, and I want to deliver the best UX to those, who will use it.

I could not notice how AppDelegate didFinishLaunchingWithOptions is similar to React useEffect, so I've really started to wonder whether we can replicate such behavior inside the JS code.

I did some tests, comparing useEffect inside a core component with a function inside didFinishLaunchingWithOptions, so the only difference I found is:

  • useEffect certainly executes only after the application started, while the iOS function would be executed during startup

I presumed, that useEffect would execute a closure every time the app is opened, but in a core component, it seems to behave the right way.

So how different is creating an SDK initialization inside, for example, useEffect and calling it from where they always put it: didFinishLaunchingWithOptions inside AppDelegate


React Native Paper the List.Accordion I can put the Icon

$
0
0

Objective

I am using the library react-native-paper and I am using the List components, but in the List.Accordion appears one strange image at the right position, I would like to put an icon arrow down in the place. But the List.Accordion just receive the left prop and no the right prop.

{bleDevices.length > 0 && (<List.Section><List.Accordion              title="Dispositivos encontrados"              left={props => <Icon name="arrow-down" size={24} />}>              {_.map(bleDevices, (device, index) => (<List.Item                  key={index}                  title={`${device.name || 'device'} (${device.rssi}) `}                  description={`${device.localName} (${device.id})`}                  right={props => (<Button onPress={toggleConnectDevice(device.name)}>                      Conectar</Button>                  )}                />              ))}</List.Accordion></List.Section>        )}

Image

enter image description here

Property 'uri' does not exist on type 'ImageSourcePropType'

$
0
0

I'd like to wrap the image component of react-native. However, an error message appears saying that 'uri' Property does not exist. Why does this happen?

import React from 'react';import { Image as DefaultImage, ImageProps } from 'react-native';import { PromiseFn, useAsync } from 'react-async';type ImageSize = {  width: number;  height: number;};const getImageSize = (uri: string) => {  return new Promise<ImageSize>((resolve, reject) => {    DefaultImage.getSize(      uri,      (width, height) => {        resolve({ width, height });      },      (error) => {        reject(error);      }    );  });};const promiseFn: PromiseFn<ImageSize> = async ({ uri }) =>  await getImageSize(uri);export function Image(props: ImageProps) {  const { source } = props;  const { data, error, isPending } = useAsync<ImageSize>({    promiseFn: promiseFn,    uri: source.uri, // Property 'uri' does not exist on type 'ImageSourcePropType'.                     // Property 'uri' does not exist on type 'number'.ts(2339)  });  return (<DefaultImage      style={[{ width: data?.width, height: data?.height }, props.style]}      {...props}    />  );}

I tried a different method, but there's another error.

const isImageURISource = (  source: ImageURISource | ImageURISource[] | ImageRequireSource) => {  if ('uri' in source) {    return source; // The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)  }};

flatlist extends out of the screen

$
0
0

I have a screen that looks like this:

return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}>       ....<View style={styles.listContainer}>          {data && showFlatList !== null && (<UsersFoundList              data={data}            />          )}</View></View></SafeAreaView>  );};  listContainer: {    justifyContent: 'center',    //marginBottom: 50,  },

I call a FlatList here from the UserFoundList component:

  return (<View><FlatList        data={data.user}        horizontal={false}        scrollEnabled        renderItem={({ item }) => (<UserFoundEntry user={item} onSendRequest={onSendRequest} />        )}        keyExtractor={(item) => item?.id?.toString()}        ListEmptyComponent={NoUsersFoundTextBox}      /></View>  );};

But the list overlaps with the safeAreaView at the bottom. While scrolling, it should appear from behind/under the SafeAreaView and not form top of it.enter image description here

Flow complains about untyped import

$
0
0

I'm starting out on a React Native project that uses react-native-geolocation-service to get the user's GPS location, but Flow is complaining that the library is untyped. The library has Typescript types, but doesn't seem to have Flow types, and VS Code gives me this error when I import the library.

Importing from an untyped module makes it any and is not safe! Did you mean to add // @flow to the top of react-native-geolocation-service? (untyped-import)Flow(LintError-untyped-import)

Can I convince Flow to stop complaining about this library, or should I switch to Typescript? I don't have any particular preference for Flow, it's just what react-native init set up for me.

I used this to create the project:

npx react-native init WarmerWalker

Then I added the library like this:

npm install react-native-geolocation-service

I import the library like this in my App.js:

import Geolocation from 'react-native-geolocation-service';

I tried adding the library to the untyped section in .flowconfig, but that didn't help. Neither did the ignore section.

The code seems to work, it's just making Flow complain.

`Cannot use import statement outside a module` when combining RN and ts-node

$
0
0

I created a small CLI tool to automate some process on my React Native project.Recently I had to update the RN from 0.61.4 to 0.63.2 to address some iOS issues.Since this update, the CLI is not working anymore.

The errors are:

yarn ts-node -r tsconfig-paths/register ./scripts/checkimport typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';^^^^^^SyntaxError: Cannot use import statement outside a module

and

yarn ts-node -r esm -r tsconfig-paths/register ./scripts/checkimport typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';       ^SyntaxError: Invalid or unexpected token

I've tried a bunch of solutions but feels that I fix A and break B, and vice-versa.Important to mention that some files from this CLI are shared with the RN app, and the RN app is working fine.

I believe I need to clear the flow typings from RN, but @babel/plugin-transform-flow-strip-types did not help

how to type event in react native with defaultPrevented?

$
0
0

i am getting an event object from react navigation with its emit function. e.g.:

  const event = navigation.emit({                type: "tabPress",                target: route.key,                canPreventDefault: true,              });

the event type from above is like this: const event: EventArg<"tabPress", any, any>but i get an error with defaultPrevented prop. e.g.:

//Property 'defaultPrevented' does not exist on type 'EventArg<"tabPress", any, any>'. if (!event.defaultPrevented) { 

i have searched and failed to find a solution, i just don't wanna use any.

(ts / React-Native) How to change an image & mp3 each N seconds with timer?

$
0
0

I'm using ts for React Native and I want to implement screen changes an image and mp3 files each seconds with timer so how can I do? I am gonna very appreciated that anybody helping me!


Functions are not valid as a React child. This may happen if you return a Component instead of from render. React native update iOS 14

$
0
0

ERROR Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Hi all, I'm updating some dependencies:

  • react-native (0.61.5) to (0.63.2)
  • react-navigation (^4.0.10) to (^4.4.0)
  • react-native-screens ^2.11.0 (new add)

Package.json:

{  ...  },"dependencies": {"@dudigital/react-native-zoomable-view": "^1.0.15","@react-native-community/async-storage": "^1.12.0","@react-native-firebase/app": "^7.1.0","@react-native-firebase/messaging": "^7.1.0","@sentry/react-native": "^1.7.2","amplitude-js": "5.5.0-react-native.1","axios": "^0.19.0","axios-extensions": "^3.0.6","date-fns": "^2.2.1","lodash": "^4.17.15","query-string": "^6.8.3","react": "16.9.0","react-native": "^0.63.2","react-native-android-dialog-picker": "^0.1.0","react-native-autogrow-textinput": "^5.3.0","react-native-background-fetch": "2.7.1","react-native-background-geolocation": "^3.4.2","react-native-background-timer": "^2.2.0","react-native-branch": "^4.3.0","react-native-camera": "^3.8.0","react-native-dash": "^0.0.11","react-native-device-info": "^5.6.5","react-native-elements": "^1.2.7","react-native-gesture-handler": "1.6.1","react-native-image-picker": "^2.2.0","react-native-keyboard-aware-scroll-view": "^0.9.1","react-native-linear-gradient": "^2.5.6","react-native-maps": "^0.25.0","react-native-material-textfield": "^0.12.0","react-native-pdf": "5.0.9","react-native-permissions": "^2.1.5","react-native-reanimated": "^1.3.0","react-native-screens": "^2.11.0","react-native-signature-capture": "^0.4.10","react-native-snap-carousel": "^3.8.4","react-native-splash-screen": "^3.2.0","react-native-svg": "^9.13.3","react-native-unimodules": "^0.7.0","react-native-vector-icons": "^6.6.0","react-native-walkme-sdk": "^2.0.12","react-native-webview": "9.4.0","react-navigation": "^4.4.0","react-navigation-hooks": "^1.1.0","react-navigation-stack": "^1.9.3","react-navigation-tabs": "^2.5.5","rn-fetch-blob": "^0.12.0","styled-components": "^4.3.2","tslint": "^5.18.0","ttag": "^1.7.18","yup": "^0.27.0"  },"devDependencies": {"@babel/core": "^7.6.2","@babel/helper-validator-identifier": "^7.9.5","@babel/runtime": "^7.6.2","@types/amplitude-js": "^4.4.4","@types/jest": "^24.0.15","@types/lodash": "^4.14.138","@types/node": "^12.6.4","@types/react": "^16.8.22","@types/react-native": "^0.57.64","@types/react-native-dotenv": "^0.2.0","@types/react-native-elements": "^0.18.0","@types/react-native-material-textfield": "^0.12.3","@types/react-native-signature-capture": "^0.4.1","@types/react-native-snap-carousel": "^3.7.4","@types/react-navigation": "^3.0.8","@types/react-test-renderer": "^16.8.2","@types/styled-components": "^4.1.16","@types/yup": "^0.26.22","@typescript-eslint/eslint-plugin": "^1.13.0","@typescript-eslint/parser": "^1.13.0","babel-jest": "^24.9.0","dtslint": "^0.8.0","eslint": "^6.5.1","eslint-config-prettier": "^6.0.0","eslint-plugin-prettier": "^3.1.0","eslint-plugin-react": "^7.14.2","husky": "^1.3.1","jest": "^24.9.0","jetifier": "^1.6.4","lint-staged": "^8.1.4","metro-react-native-babel-preset": "^0.56.0","prettier": "^1.18.2","react-native-asset": "1.1.4","react-native-dotenv": "^0.2.0","react-test-renderer": "16.9.0","reactotron-react-native": "^4.0.2","tslint-config-prettier": "^1.18.0","tslint-react": "^4.0.0","tslint-react-hooks": "^2.2.1","ttag-cli": "^1.7.22","typescript": "3.5.2","typescript-styled-plugin": "^0.15.0"  },"jest": {"preset": "react-native"  }}

App.tsx:

import React, { useEffect, useState, useRef } from 'react';import { PermissionsAndroid, Platform, Alert } from 'react-native';import branch from 'react-native-branch';import { NavigationState, NavigationContainer } from 'react-navigation';import { ThemeProvider } from 'styled-components';import SplashScreen from 'react-native-splash-screen';import amplitude from 'amplitude-js';import AmplitudeClient from 'amplitude-js';import DeviceInfo from 'react-native-device-info';import { useLocale } from 'ttag';import messaging from '@react-native-firebase/messaging';import getAppNavigator from './navigation/AppNavigator';import config from './config';import theme from './theme';import { getItem, setItem } from './utils/storage';import { getActiveRouteName, getActiveRouteParams } from './navigation/utils';import { fetchToken, AccessToken, FetchTokenParams } from './services/auth';import { areParamsForOnboarding } from './services/branch';import { usePublicFetch } from './hooks/fetching';import { LocaleProvider, Locale, updateLocale, getLocaleFromStorage } from './locale';const App = () => {  const [AppNavigator, setAppNavigator] = useState<NavigationContainer>();  const branchParams = useRef<branch.Params>();  const [query, fetchTokenParams] = usePublicFetch<AccessToken, FetchTokenParams>(fetchToken);  const [realizarQuery, setRealizarQuery] = useState(true);  function finishLoading(accessToken?: string, refreshToken?: string) {    if (accessToken && refreshToken) {      config.accessToken = accessToken;      config.refreshToken = refreshToken;    }    setAppNavigator(() => {      if (branchParams.current && areParamsForOnboarding(branchParams.current)) {        return getAppNavigator(!!accessToken, {          companyId: branchParams.current.companyId,          newCompany: branchParams.current.newCompany,          travelOrderId: branchParams.current.travelOrderId,        });      }      return getAppNavigator(!!accessToken);    });    SplashScreen.hide();  }  useEffect(() => {    (async () => {      const accessToken = await getItem('accessToken');      const refreshToken = await getItem('refreshToken');      const p = await branch.getLatestReferringParams();      if (accessToken && refreshToken) {        finishLoading(accessToken, refreshToken);      } else if (areParamsForOnboarding(p)) {        branchParams.current = p;        fetchTokenParams({          user: p.username,          pass: p.authorizationcode,        });      } else {        finishLoading();      }    })();  }, []);  useEffect(() => {    if (query.data && realizarQuery) {      setRealizarQuery(false);      finishLoading(query.data.access_token, query.data.refresh_token);      savingToken(query.data.access_token, query.data.refresh_token);    }  }, [query]);  if (!AppNavigator) {    return null;  }  return (<AppNavigator      onNavigationStateChange={(prevState: NavigationState, currentState: NavigationState) => {        const currentScreen = getActiveRouteName(currentState);        const prevScreen = getActiveRouteName(prevState);        const params = getActiveRouteParams(currentState);        if (prevScreen !== currentScreen) {          // We also update amplitude every single time a navigation occurs          amplitude.getInstance().logEvent(`${currentScreen.toLowerCase()}.viewed`, params);        }      }}    />  );};export default () => {  const [locale, setLocale] = useState<Locale>('en');  useEffect(() => {    getLocaleFromStorage().then(storedLocale => {      useLocale(storedLocale); // ttag change of locale      setLocale(storedLocale);    });  }, []);  return (<ThemeProvider theme={theme}><LocaleProvider        value={{          locale,          setLocale: (locale: Locale) => {            updateLocale(locale); // ttag & async storage change of locale            setLocale(locale);          },        }}><App /></LocaleProvider></ThemeProvider>  );};

In App.tsx the problem is that I get an issue related with the function, getAppNavigator(!!accessToken):NavigationContainer this is because is a function and it's expecting an JSX.element like this:

AppNavigator:NavigationContainer

Q: It's possible to keep using a function as a NavigationContainer ?

Screenshot of the issue

Thank you so much!

getting Property 'value' does not exist on type 'number'.ts(2339) on onChange function of react native text input

$
0
0

Hey im relatively new to typescript. Its telling me there's no value property on the e.target attribute of my onChange function. Im just trying to have it update the state of the userObj, allow me to save that data, and then let me view that data in another component.

import React, { useState } from 'react';import {    View,    Image,    Text,    TextInput,    StyleSheet,    SafeAreaView,    KeyboardAvoidingView,  } from 'react-native';import { TouchableOpacity, ScrollView } from 'react-native-gesture-handler';import profile from '../assets/IMG_7767.psd'import UserStore from '../store/UserStore'interface Props {}  const Profile: React.FC<Props> = () =>  {    const { user } = UserStore     const [firstName, setFirstName] = useState(user[0].firstName)    const [lastName, setLastName] = useState(user[0].lastName)    const [location, setLocation] = useState(user[0].location)    const [description, setDescription] = useState(user[0].description)    const userObj = {      firstName: firstName,      lastName: lastName,      location: location,      description: description    }    return (<SafeAreaView style={styles.blue}><KeyboardAvoidingView><ScrollView><View style={styles.center}><View style={styles.head}><Text style={styles.headText}>Profile Details</Text></View><View style={styles.shadow}><Image source={profile} style={styles.profileImage}/></View><View style={styles.formField}><Text style={styles.formText}>First Name</Text><TextInput                   style={styles.textInput}                   value={firstName}                   onChange={(e) => setFirstName(e.currentTarget)}                  /></View><View style={styles.formField}><Text style={styles.formText}>Last Name</Text><TextInput                   style={styles.textInput}                  value={lastName}                   onChange={(e) => setLastName(e.target.value)}                  /></View><View style={styles.formField}><Text style={styles.formText}>Location</Text><TextInput                   style={styles.textInput}                  value={location}                   onChange={(e) => setLocation(e.target.value)}                  /></View><View style={styles.formField}><Text style={styles.formText}>Description</Text><TextInput                   style={styles.textArea}                  value={description}                   onChange={(e) => setDescription(e.target.value)}                  /></View><TouchableOpacity style={styles.mainButton} onPress={()=> user[0].update(userObj)}><Text style={styles.mainButtonText}>Save</Text></TouchableOpacity></View></ScrollView></KeyboardAvoidingView></SafeAreaView>    )}

I looked at other posts on stack overflow and couldn't find any related to this specific issue. Other solutions i found online said to use getElementById().value but i figured there would be an easier way pithing react-native. I also saw a solution that said e.currentTarget instead of e.target Im assuming that would have the same result as Im currently having because its ties to an onChange attribute and only one text input is changing at a time. The second solution did not work for me either

How to use prop-types as type definition in typescript?

$
0
0

Situation:

Consider having the myTypes constant holding prop-types (written somewhere in a file called my-component.js), like below:

import React from 'react'import { View } from 'react-native'import PropTypes from 'prop-types'export const myTypes = {  activeColor: PropTypes.string,  color: PropTypes.string,  fontFamily: PropTypes.string,  fontSize: PropTypes.number,  fontWeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),  height: PropTypes.number,  icon: PropTypes.node,  iconOverlay: PropTypes.node,  marginBottom: PropTypes.number,  marginLeft: PropTypes.number,  marginRight: PropTypes.number,  marginTop: PropTypes.number,  maxHeight: PropTypes.number,  minHeight: PropTypes.number,  onBlur: PropTypes.func,  onChangeText: PropTypes.func,  paddingBottom: PropTypes.number,  paddingLeft: PropTypes.number,  paddingRight: PropTypes.number,  paddingTop: PropTypes.number}export default class MyComponent extends React.Component {  static propTypes = myTypes  render () {    return (<View></View>    );  }}

How would you use myTypes as a type or helper to enable IDE auto-completion?

What I tried (in another file written in type-script as well) is below:

import MyComponent, { myTypes } from 'my-component';const dark_theme_properties: myTypes = {  activeColor: 'green'};

But of course, that gives the 'myTypes' refers to a value, but is being used as a type here. ts(2749) error.


Edit: the question in the old title was "How to use a value as a type definition in typescript?", which thanks to the answers, I now know would be as simple as using typeof keyword, like:

const dark_theme_properties: typeof myTypes = {  activeColor: 'green'  // ...};

Getting "Invalid call" when using require with Typescript and Expo

$
0
0

I am trying to play some audio in a react-native app created with the expo-cli.

The code is written in typescript and the offending code looks like this, taken from the expo.io documentation:

import * as React from 'react'import { WorkoutComponent } from "./WorkoutExecutor";import { Audio } from 'expo';export default class AudioPlayer {    private async playAudio(fileName: string) {        console.log("Playing Audio: "+ fileName);        const soundFile = './assets/sounds/'+ fileName +'.mp3';        try {            const { sound: soundObject, status } = await Audio.Sound.createAsync(              require(soundFile),              { shouldPlay: true }            );            // Your sound is playing!          } catch (error) {              console.log(error);            // An error occurred!          }    }[...]}

When the app loads, it gives the following error, even before it gets to the screen with the sound

[...]\src\AudioPlayer.ts:Invalid call at line 13: require(soundFile)

I realize that the coe example is with javascript and not typescript, but what am I missing?

My tsconfig.json is the one from the expo typescript example and looks like this

{"compilerOptions": {"baseUrl": "./src","esModuleInterop": true,"experimentalDecorators": true,"forceConsistentCasingInFileNames": true,"importHelpers": true,"jsx": "react-native","module": "es2015","moduleResolution": "node","noEmitHelpers": true,"noImplicitReturns": true,"noUnusedLocals": true,    // Using the type definitions in @types/expo becuase they are still better than the ones provided by expo. See SvgScreen.tsx and SystemFontsScreen.tsx."paths": {"expo": ["../node_modules/@types/expo","../node_modules/expo"      ],    },"skipLibCheck": true,"strict": true,"target": "es2017"  },"exclude": ["node_modules"  ]}

how to pass ref from parent to child Touchable Opacity in react native?

$
0
0

i have a transitioning ref in a parent Transitioning view i want to pass in a child:

const transition = (<Transition.Together><Transition.In type="fade" durationMs={300} /><Transition.Change /><Transition.Out type="fade" durationMs={300} /></Transition.Together>);const FiltersModal: FC = () => {const transitionRef = useRef<TransitioningView>(null);return (<FiltersContainer ref={transitionRef} transition={transition}> ...{primaryFilters.map((primaryFilter, i) => (<FilterOption key={i} ref={transitionRef} label={primaryFilter}>      {primaryFilter}</FilterOption>  ))}

and this is my filter option following an answer from here: ForwardRef error with typescript and react-native:

const FilterOption: React.ComponentType<FilterOptionProps> = React.forwardRef(  ({ label }: FilterOptionProps, ref?: React.Ref<TransitioningView>) => {    const [isSelected, setiIsSelected] = useState(false);    const onPress = () => {      if (ref.current) ref.current.animateNextTransition();      setiIsSelected((prevIsSelected) => !prevIsSelected);    };    if (isSelected) return null;    return (<Button><Typography          {...{            fontFamily: FONTS_MONTSERRAT_500,            fontWeight: 500,            fontSize: 14,            fontStyle: "normal",            lineHeight: 20,            color: "#00B0F0",          }}>          {label}</Typography><AntDesign name="plus" color="#00b0f0" size={10} /></Button>    );  });

but i have this warning and cannot referrence ref.current.:

Type 'ForwardRefExoticComponent<Pick<FilterOptionProps, "label"> & RefAttributes<TransitioningView>>' ....

How do i use forwardref in a touchableOpacity in react native + typescript?

type for native-base-theme material

$
0
0

https://docs.nativebase.io/Customize.html#theaming-nb-headref

I am using a custom native-base style theme according to the link above.

import material from './native-base-theme/variables/material';import getTheme from './native-base-theme/components';
return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}>

On material, I get such TypeScript errors:

Argument of type '{ platformStyle: string; platform: "ios" | "android" | "windows" | "macos" | "web"; headerStyle: string; iconStyle: string; contentStyle: string; expandedIconStyle: string; accordionBorderColor: string; ... 151 more ...; Inset: { ...; }; }' is not assignable to parameter of type '{ platformStyle: any; platform: "ios" | "android" | "windows" | "macos" | "web"; accordionBorderColor: string; accordionContentPadding: number; accordionIconFontSize: number; contentStyle: string; ... 180 more ...; Inset: { ...; }; }'.Type '{ platformStyle: string; platform: "ios" | "android" | "windows" | "macos" | "web"; headerStyle: string; iconStyle: string; contentStyle: string; expandedIconStyle: string; accordionBorderColor: string; ... 151 more ...; Inset: { ...; }; }' is missing the following properties from type '{platformStyle: any; platform: "ios" | "android" | "windows" | "macos" | "web";

How can I get rid of this?

material.js inside the native-base-themes folder looks like this:

import color from 'color';import { Platform, Dimensions, PixelRatio } from 'react-native';import { PLATFORM } from './commonColor';const deviceHeight = Dimensions.get('window').height;const deviceWidth = Dimensions.get('window').width;const platform = Platform.OS;const platformStyle = PLATFORM.MATERIAL;const isIphoneX =  platform === PLATFORM.IOS &&  (deviceHeight === 812 ||    deviceWidth === 812 ||    deviceHeight === 896 ||    deviceWidth === 896);export default {  platformStyle,  platform,  // Android  androidRipple: true,  androidRippleColor: 'rgba(256, 256, 256, 0.3)',  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',  buttonUppercaseAndroidText: true,  // Button  buttonFontFamily: 'Roboto',  get buttonPrimaryBg() {    return this.brandPrimary;  },  get buttonTextSizeLarge() {    return this.fontSizeBase * 1.5;  },  // Header  toolbarBtnColor: '#fff',  toolbarDefaultBg: '#3F51B5',  toolbarHeight: 56,  toolbarSearchIconSize: 23,  toolbarInputColor: '#fff',  searchBarHeight: platform === PLATFORM.IOS ? 30 : 40,  searchBarInputHeight: platform === PLATFORM.IOS ? 40 : 50,  toolbarBtnTextColor: '#fff',  toolbarDefaultBorder: '#3F51B5',  iosStatusbar: 'light-content',  get statusBarColor() {    return color(this.toolbarDefaultBg)      .darken(0.2)      .hex();  },  get darkenHeader() {    return color(this.tabBgColor)      .darken(0.03)      .hex();  },  // Text  textColor: '#000',  inverseTextColor: '#fff',  noteFontSize: 14,  get defaultTextColor() {    return this.textColor;  },  // iPhoneX SafeArea  Inset: {    portrait: {      topInset: 24,      leftInset: 0,      rightInset: 0,      bottomInset: 34,    },    landscape: {      topInset: 0,      leftInset: 44,      rightInset: 44,      bottomInset: 21,    },  },};

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts

$
0
0

I am using redux-saga and redux-actions with Typescript, like this:

 const moviesReducer = handleActions(      {        [actions.fetchMovies]: (state) => ({          ...state,          details: {...initialState.details},        }),        [actions.fetchMoviesSuccess]: (state, action) => {          return {            ...state,            details: {...state.details, ...action.payload},          };        },        [actions.fetchMoviesFailed]: (state, {payload}) => ({          ...state,          error: payload,        }),      },      initialState,    );

I have tried many answers from here:Typescript setState with computed property names

but nothing fits my case.

I got the error to go doing this:

[actions.fetchMovies.toString()]: (state) => ({  ...state,  details: {...initialState.details},}),

But I am afraid that may cause issues later onAny insight would be appreciated.

Thank you.


What is the meaning of this code in React Native and Typescript?

$
0
0

I have read some codes of my company's project and see something strange and do not know what it is.

What is the meaning of the last '&' and an object { invalidMail?: string, ... }?

const InputValidation: React.ForwardRefExoticComponent<  React.PropsWithoutRef<IInputValidationProps> & React.RefAttributes<TextInput>> & {  invalidMail?: string;  invalidNumber?: string;  invalidPhone?: string;  isRequired?: string;  notPositiveNumber?: string;  lessThanMinLength?: string;} = forwardRef<TextInput, IInputValidationProps>((props, ref) => { ... }InputValidation.invalidMail = 'Mail không hợp lệ';InputValidation.invalidNumber = 'Số không hợp lệ';InputValidation.invalidPhone = 'Sốđiện thoại không hợp lệ';InputValidation.isRequired = 'Bắt buộc';InputValidation.notPositiveNumber = 'Không nhận giá trịâm';InputValidation.lessThanMinLength = 'Số kí tự tối thiểu ';

Does anybody know how this code affect InputValidation component? Thank in advance.

React Native: Array.map()-based rendered components not updating on state change

$
0
0

I have a few components being rendered from an Array.map() that won't update even when the state (pertaining to said array) changes, and I have no clue why this is.

Home (main component) :

import React, { useState } from 'react';import { View, TouchableOpacity } from 'react-native';import { base } from './data';import Indicator from './components/Indicator';const Home = () => {  const [switches, setSwitches] = useState(base);  const handleToggle = (id: number) => {    base.map(switch => {      switch.on =        (switch.on && switch.id !== id) || (!switch.on && switch.id === id)          ? !switch.on          : switch.on;    });    setSwitches(base);  };  return (<View>      {switches.map(switch => (<TouchableOpacity          onPress={() => handleToggle(switch.id)}          key={switch.id}><Indicator            color={switch.color}            on={switch.on}          /></TouchableOpacity>      ))}</View>

Indicator component:

import React from 'react';import { View } from 'react-native';import { On, Off } from './Indicators';interface IndicatorProps {  color: string;  on: boolean;}const Indicator: React.FC<IndicatorProps> = ({ color, on }) => {  return (<View>      {on ? <On /> : <Off />}</View>  );};export default Indicator;

I have verified that the state of switches is changing as expected when clicking the touchable areas, but no visible change occurs in the components.

Logout on Apollo-Client

$
0
0

I'm developing an app using react-native with Expo that interacts with a GraphQL Backend using Apollo.

The authorization between Front and Back is done with JWT token on header and it's working fine. On backend there is a Middleware that checks if the token exists and is valid:

  • If the query is open, it just retrieve the info.
  • If the query is authorized and the user is authenticated it retrieves the info.
  • If the query is authorized but the user is not logged in (or using an invalid token) it throws an error.

BACKEND

export const isAuth: MiddlewareFn<MyContext> = ({ context }, next) => {    const { authorization } = context.req.headers;    if (!authorization) {        throw new Error("Not authenticated. ");    }[...]}@Query(() => User)@UseMiddleware(isAuth)async Me(    @Ctx() { payload }: MyContext,) {    return UserModel.findById(payload!.userId);}

The way I'm getting the queryes is through the following component:

FRONTEND

const Me: React.FC<any> = (props) => {    const {        data, loading, error,    } = useMeQuery();    if (loading) {        return (<Text>Loading ... {String(props.test)}</Text>);    }    if (error) {        return (<Text>{ error.message } {String(props.test)}</Text>);    }    return (<Text>Hello { String(data?.Me?.email) } </Text>    );};

Being useMeQuery(); a hook function generated by @graphql-codegen/cli.

export function useMeQuery(baseOptions?: ApolloReactHooks.QueryHookOptions<MeQuery, MeQueryVariables>) {        return ApolloReactHooks.useQuery<MeQuery, MeQueryVariables>(MeDocument, baseOptions);}

Up to here it is working fine.

Now, I'm trying to implement the Logout functionallity on the frontend so the user can keep navigating as an anonimous user when logged out.

I just created a button that calls a function that clears the stored tokens (it is working), so the next calls are not authenticated and throws an error. The problem I'm getting on is that apollo-client is using cache to rerender the query, so the now anonimous user is able to see the old-LogedIn user information.

In order to Logout, I tried several ways to clear cache, without succeed:

clearTokens(); // Clear tokens from asyncStorage. Working fine.// Tying to clear cache:client.clearStore(); // Not working, still getting the stored value on cache when refreshing the component.client.cache.reset(); // Not working, still getting the stored value on cache when refreshing the component.client.resetStore(); // Not working, it tries to call the query again, it throws an error (because it is not authenticated) and doesn't clear the cache.

Which is the best way in order to Logout when using apollo-client?

PD: If another user is logged in, I call the client.resetStore(); and the queryes all refetched, working properly. The problem is just to pass from loggedIn to anonimous.

How do I make thefun.thefun a function?

$
0
0

Technology:React-Native

Desired Result:I'm trying to pass a function between components. I want theFun.theFun() to call but it doesn't run:

Component ExceptiontheFun.theFun is not a function. (In 'theFun.theFun("2", "1", "blueShrimp"). 'theFun.theFun' is undefined

What I've Tried:I've tried {storeMeaturement} vs {()=> storeMeasurement("2","1","blueShrimp"} vs { storeMeasurement("2","1","blueShrimp"} in the component definition and theFun={storeMeasurement} vs theFun={storeMeasurement("2","1","blueShrimp")} in the tag. I've tried other things too to no avail.

Here is the code:

Where I use the tag

<ModalPurpleCard theList={["10","91","thermometer"]}  theFun={storeMeasurement} ></ModalPurpleCard>

Where I define the tag

function ModalPurpleCard(theList:any, theFun:any ) {// , theFun:function  let [visOpen, setVisOpen] = React.useState(true);  let [stillLoad, setStillLoad] = React.useState(true);  //let theFig = Math.round(Math.random() *10 + 90)  let theFig = Number(theList.theList[0]) + Number(theList.theList[1])  console.log(theFig)  if (visOpen){    return(<TouchableOpacity onPress={()=> setVisOpen(false)}><View style={{zIndex:3}}><ModalSecCard  ><Text style={{color:"#fff"}}>{theList.theList[2]}</Text></ModalSecCard></View></TouchableOpacity>    )  } else{      if(stillLoad){        return(<TouchableOpacity onPress={theFun.theFun("2","1","blueShrimp")}><ActivityIndicator animating={true} color="#333366"/></TouchableOpacity>        )      } else {return(<Text>{theFig}</Text>  )}  }}

Conclusion:The weird thing for me is that theList works great and successfully passes between components. The function, however, does not.

ApolloClient client's Type

$
0
0

I have a function where I pass the client as a parameter and delete the token from my app etc:

  const logOut = async (client: ApolloClient<unknown>) => {...};
return (<ApolloConsumer>      {(client: ApolloClient<unknown>) => (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.buttonContainer}><Button                  onPress={() => logOut(client)}                  style={styles.button}                /></View></SafeAreaView>      )}</ApolloConsumer>  );};

Right now I am using unknownfor the ApolloClient type and it works. But what should I actually be using here?

Viewing all 6214 articles
Browse latest View live


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