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

How to create global android device back button handler using React Native?

$
0
0

In my scenario, I am trying to create global class for android back button handler and reuse it in multiple screen class files. How to do it? I tried below code but I dont know how to access common class from other classes.

My Code Below (Androidhandler.tsx)

export default class hardware extends Component {  constructor(props) {    super(props);    this.BackButton = this.BackButton.bind(this);  }  componentWillMount() {    BackHandler.addEventListener'BackPress',this.BackButton);  }  componentWillUnmount() {    BackHandler.removeEventListener('BackPress',this.BackButton);  }  BackButton() {    if(this.props.navigation){        this.props.navigation.goBack(null);        return true;      }    }}

Module '"@react-native-firebase/firestore"' has no exported member 'CollectionReference'. ts(2614)

$
0
0

I use TypeScript and React native with Firestore (no expo).

On the import:

import { CollectionReference } from '@react-native-firebase/firestore'

I get the error message:

Module '"@react-native-firebase/firestore"' has no exported member 'CollectionReference'. Did you mean to use 'import CollectionReference from "@react-native-firebase/firestore"' instead?ts(2614)

I installed the module, trying both yarn and npm install.

Here is the packages.json points of interest:

{"dependencies": {"@react-native-firebase/app": "^8.4.3","@react-native-firebase/auth": "^9.2.3","@react-native-firebase/dynamic-links": "^7.5.4","@react-native-firebase/firestore": "^7.8.2","@react-native-firebase/storage": "^7.4.3",    ...  },"devDependencies": {,"ts-node": "^8.10.2","typescript": "^3.9.7"    ...  },}

I can still use @firebase/firestore-types instead but this package is specified as:

This package is not intended for direct usage, and should only be used via the officially supported firebase package.

This is the web pakage, not the one for React Native Firebase.

InvariantViolation exceptions on react native expo

$
0
0

I keep running into similar type of exceptions over and over again:

"Invariant Violation: requireNativeComponent: "ToolbarAndroid" was notfound in the UIManager"

Configuration: running on android, react native 0.63.0, used expo init project-name, expo-cli 3.27.10, typescript

Tried:

npm install expo install @react-native-community/toolbar-android // installs "@react-native-community/toolbar-android": "0.1.0-rc.2"expo install @react-native-community/toolbar-android // installs "@react-native-community/toolbar-android": "0.1.0-rc.2"

All I can find on the web is: "tRy NpX poD-iNsTAll", but as far as I understand it's for iOS, so it returns "not a darwin machine".I understand it could be something wrong with linking, but react-native 0.60.0+ solves this automatically, so what's going on? Incompatible versions?

could not locate shadow view with tag

$
0
0

My React Native application has a screen HomeScreen (it is not the first screen that we see when we open the screen). Upon visiting this screen, I don't see any warning.

From the HomeScreen, I visit another screen, followed by another etc. Then, when I return to the HomeScreen, I see this warning:

Could not locate shadow view with tag #5469, this is probably caused by a temporary inconsistency between native views and shadow views.

The Navigation scheme is somewhat like this:

export type AppStackParamList = {  Home: undefined;  AddFriend: undefined;  AllFavouriteLocations: undefined;  EditFavouriteLocation: undefined;}const NavigationStack = createStackNavigator<AppStackParamList>();....return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}><ApolloProvider client={client}><SafeAreaProvider><NavigationContainer><NavigationStack.Navigator                  initialRouteName="Test"                  screenOptions={{                    gestureEnabled: false,                  }}><NavigationStack.Screen                    name="Test"                    component={TestScreen}                    options={{ headerShown: false }}                  /><NavigationStack.Screen                    name="Home"                    component={HomeScreen}                    options={{ headerShown: false }}                  /><NavigationStack.Screen                    name="AddFriend"                    component={AddFriendScreen}                    options={{                      headerShown: false,                    }}                  /></NavigationStack.Navigator></NavigationContainer></SafeAreaProvider></ApolloProvider></StyleProvider></Provider></Suspense>  );};

HomeScreen:

return (<View style={styles.container}><View style={styles.mapContainer}><MapContainer /></View><HamburgerIcon /><HomeSwipeablePanel /><View style={styles.buttonContainer}><EnterDestinationButton          resetLocation={resetLocation}          navigation={navigation}          locations={locations}        /></View></View>  );};const styles = StyleSheet.create({  mapContainer: {    flex: 3,  },  container: {    flex: 1,  },  buttonContainer: {    position: 'absolute',    width: '100%',    height: moderateScale(SCREEN_HEIGHT * 0.1),    bottom: scale(5),    alignItems: 'center',  },});

What could be the reason for this warning?

React hooks - Updated state not re-rendering

$
0
0

Using the following useEffect hook, the updated state is not rendered unless the user touches the screen or even if we place a console.log under the effect (as indicated in the snippet below):

 export const ExerciseForm = ({  definition: { id },}: {  definition: ExerciseDefinition;}) => {  const initialSet: Set[] = [{ reps: 0, value: 5 }];  const [sets, setSets]: [Set[], Dispatch<Set[]>] = useState(initialSet);  // Reset form if definition ID changes  useEffect(() => {    setSets(initialSet);  }, [id]);  // Uncommenting this will make it the rerender work??  // console.log('id', id);

Each id is obviously unique and can confirm that it is updating correctly higher in the component tree from which the prop is passed. I realise this is a common issue, however, none of the similar answers on S/O (or elsewhere on the internets) has yielded a proper solution.

Full components can be found below:

ExerciseForm.tsx

import React, { useState, Dispatch, useEffect } from 'react';import { ExerciseDefinition, Set } from '../constants/Interfaces';import { ScrollView, View } from 'react-native';import { Input, Button } from 'react-native-elements';export const ExerciseForm = ({  definition: { id },}: {  definition: ExerciseDefinition;}) => {  const initialSet: Set[] = [{ reps: 0, value: 5 }];  const [sets, setSets]: [Set[], Dispatch<Set[]>] = useState(initialSet);  // Reset form if definition ID changes  useEffect(() => {    setSets(initialSet);  }, [id]);  // Uncommenting this will make it the rerender work??  // console.log('id', id);  const updateSet = (index: number, field: 'reps' | 'value', value: string) => {    const updatedSets = [...sets];    updatedSets[index][field] = parseInt(value);    setSets(updatedSets);  };  const addSet = () => {    const updatedSets = [...sets, { ...sets[sets.length - 1] }];    setSets(updatedSets);  };  return (<ScrollView>      {sets.map(({ reps, value }: Set, index: number) => (<View key={index}><Input            label="Reps"            keyboardType="numeric"            value={reps ? reps.toString() : ''}            onChange={({ nativeEvent }) =>              updateSet(index, 'reps', nativeEvent.text)            }          /><Input            label="Weight"            keyboardType="numeric"            value={value ? value.toString() : ''}            onChange={({ nativeEvent }) =>              updateSet(index, 'value', nativeEvent.text)            }          /></View>      ))}<Button title="Add set" onPress={() => addSet()} /></ScrollView>  );};

HomeScreen.tsx

import React, {  useContext,  useReducer,  useEffect,  useState,  Dispatch,} from 'react';import {  StyleSheet,  Picker,  ScrollView,  ActivityIndicator,} from 'react-native';import { Text } from '../components/Themed';import { UserContext } from '../services/context';import {  exerciseDefinitionReducer,  initialExerciseDefinitionState,  exerciseDefinitionActions,} from '../reducers/exerciseDefinition';import { ExerciseDefinition } from '../constants/Interfaces';import { ExerciseForm } from '../components/ExerciseForm';export default function HomeScreen() {  const {    state: { firstName },  } = useContext(UserContext);  const [{ definitions, loading }, definitionDispatch] = useReducer(    exerciseDefinitionReducer,    initialExerciseDefinitionState  );  const [selectedDefintion, setSelectedDefinition]: [    ExerciseDefinition | undefined,    Dispatch<ExerciseDefinition>  ] = useState();  // Get definitions on mount  useEffect(() => {    exerciseDefinitionActions(definitionDispatch).getDefinitions();  }, []);  // Set default definition to first item  useEffect(() => {    !selectedDefintion && setSelectedDefinition(definitions[0]);  }, [definitions]);  return (<ScrollView><Text style={styles.title}>{firstName}</Text>      {loading && <ActivityIndicator />}      {/* TODO: decide whether to use this R/N Picker or NativeBase picker */}<Picker        selectedValue={selectedDefintion?.id}        onValueChange={(id) => {          const definition = definitions.find((def) => def.id === id);          definition && setSelectedDefinition(definition);        }}>        {definitions.map((defintion) => {          const { title, id } = defintion;          return <Picker.Item key={id} label={title} value={id} />;        })}</Picker>      {selectedDefintion && <ExerciseForm definition={selectedDefintion} />}</ScrollView>  );}const styles = StyleSheet.create({  container: {    flex: 1,    alignItems: 'center',    justifyContent: 'center',  },  title: {    fontSize: 20,    fontWeight: 'bold',  },  separator: {    marginVertical: 30,    height: 1,    width: '80%',  },});

(Edit 29/09/2020)

Interestingly, neither of the following console.logs are executed either until the user touches the screen (or the noted commented lined is uncommented), suggesting that the issue is certainly to do with the useEffect statement or its dependency:

  // Reset form if definition ID changes  useEffect(() => {    console.log('old ID', id);    setSets(initialSet);    console.log('new ID', id);  }, [id]);  // Uncommenting this will make it the rerender work??  // console.log('id', id);

How to define this interface Props so that this Props contains all the attributes of the passed component

$
0
0
interface Props {    component: any;}function Example(props: Props) {    const {component: Component, children} = props    return <Component>{children}</Component>}

For example: the incoming component is TouchableOpacity in react-native,then the Example component automatically inherits all Props of TouchableOpacity.You can write like this and Typescript does not report errors:

<Example component={TouchableOpacity} onPress={handleSomePress} />

I am a newbie to TypeScript, this problem has bothered me for a long time.Looking forward to a perfect answer, pray.

How do I configure absolute paths for imports in TypeScript based React Native apps?

$
0
0

In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.

It is important that the configuration also supports Jest unit tests.

I created the app using npx react-native init MyTestApp --template typescript

React Native version: 0.60.5

What is the exact configuration I would need to achieve this?

Type 'ApolloClient' is missing the following properties from type 'ApolloClient'

$
0
0

I am trying to do authentication using Apollo Client and a token placed in header. I am trying something like this:

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';import { setContext } from '@apollo/client/link/context';import { NormalizedCacheObject } from 'apollo-cache-inmemory';import { ApolloProvider } from '@apollo/react-hooks';...const httpLink = createHttpLink({  uri: 'https://graphql',});const authLink = setContext((_, { headers }) => {  const token = 'XX';  return {    headers: {      ...headers,      authorization: token ? `Bearer ${token}` : "",    }  }});const client = new ApolloClient({  link: authLink.concat(httpLink),  cache: new InMemoryCache()});...<ApolloProvider client={client}><BrowserRouter><App /></BrowserRouter></ApolloProvider>

However, I keep getting a type error on Apollo Provider that:

Type 'ApolloClient<NormalizedCacheObject>' is missing the following properties from type 'ApolloClient<any>': store, writeData, initQueryManager

This makes the app crash. I am not manually using NormalizedCacheObject anywhere. How can I fix this?


type for navigation 'replace' function

$
0
0

My navigationStack looks somewhat like this. For now, I am using the type anyfor my route (in replace). What's the correct type I should be using?

const NavigationStack = createNativeStackNavigator<LoginStackParamList>();export type LoginStackParamList = {  PasswordLogin: undefined | { login: boolean };  Login: undefined;  replace: (route: any) => void;};

import components with ~ instead of './'

$
0
0

In my pages/screens folder, I made an index file and did something like this:

export * from './UserPage';export * from './users/SearchPage';

So now, when I want to import components from these pages in my App.tsx file, I can just

import { SearchPage, NewPage } from './pages'; 

instead of typing the full relative path. However, I want to use something like

import { SearchPage, NewPage } from '~/pages'; 

For this, I added this into my tsconfig.json file as it seemed to work in another project but it's not working for me here:

"paths": {"~/*": ["./*"],"~": ["./"]    },

How else can I change my import format?

Edit:tsconfig.json:

{"compilerOptions": {"target": "es5","lib": ["dom","dom.iterable","esnext"    ],"allowJs": true,"skipLibCheck": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"strict": true,"forceConsistentCasingInFileNames": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "preserve","baseUrl": "./src","paths": {"@modules/*": ["modules/*"],"@config/*": ["config/*"],"@shared/*": ["shared/*"]    },  },"include": ["src"  ]}

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} />)}

Platform specific import component in react native with typescript

$
0
0

I am using react native with typescript. I have a component with the following structure

component    - component.ios.tsx    - component.android.tsx

Now I want to import the component. So, I am doing this:

import component from '../component/component';

But it says:

[ts] Cannot find module ../component/component

The location is correct. I need to add something to the tslint file to make it understand.

I also tried to do:

let component = require('../component/component');

This didn't give typescript error. But it gave a runtime error.

element type is invalid expected a string or a class/function but got undefined

Has anybody run into this issue?Thank you.

Extends Console Interface for TypeScript

$
0
0

I would like to add an object in the window.console global.

import Reactotron from 'reactotron-react-native';window.console.tron = Reactotron;

Although when I do that, TypeScript complains about the new object:

error TS2339: Property 'tron' does not exist on type 'Console'.

I was thinking to extends the Console interface:

interface ConsoleWithTron extends Console {  tron: any};

Although, I'm not sure how to assign this new interface to my global console object?

Help would be great!

Thanks.

How to combine tab and stack navigation props in reactnavigation typescript react native

$
0
0

I am trying to combine two navigation props But I am not sure how to do this. Earlier when I used to define only one route I used to do something like this.

    export type MatrimonyStackRoutes = {      Matrimony: undefined;      GroomDetail: undefined;    };    export type MatrimonyStackNavigationProps<      T extends keyof MatrimonyStackRoutes> = {      navigation: StackNavigationProp<MatrimonyStackRoutes, T>;      route: RouteProp<MatrimonyStackRoutes, T>;    };<Stack.Navigator><Stack.Screen name="Matrimony" component={MatrimonyTab} /><Stack.Screen name="GroomDetail" component={GroomDetail} /></Stack.Navigator>

And Inside component I used to declare like this

const Groom = ({ navigation }: MatrimonyStackNavigationProps<"Matrimony">) => {  return (    //////////  );};

This works fine But Now I am in need to combine two routes stack and bottomTab props show that I can use in my component in similar way.I am not sure how to do that any help would be great.

Here Is my Complete Code of both Tab And stack navigation when it is not combined

    export type MatrimonyTabRoutes = {      Groom: undefined;      Bride: undefined;      Vendors: undefined;    };    export type MatrimonyStackRoutes = {      Matrimony: undefined;      GroomDetail: undefined;    };    export type MatrimonyStackNavigationProps<      T extends keyof MatrimonyStackRoutes> = {      navigation: StackNavigationProp<MatrimonyStackRoutes, T>;      route: RouteProp<MatrimonyStackRoutes, T>;    };    export type MatrimonyTabNavigationProps<T extends keyof MatrimonyTabRoutes> = {      navigation: BottomTabNavigationProp<MatrimonyTabRoutes, T>;      route: RouteProp<MatrimonyTabRoutes, T>;    };const MatrimonyTab = ({}) => {  const theme = useTheme();  return (<Tab.Navigator      tabBarOptions={{        activeTintColor: theme.colors.primaryText,        inactiveTintColor: theme.colors.grey,        indicatorStyle: {          backgroundColor: theme.colors.mainIconColor,        },      }}><Tab.Screen name="Groom" component={Groom} /><Tab.Screen name="Bride" component={Bride} /><Tab.Screen name="Vendors" component={Vendors} /></Tab.Navigator>  );};const MatrimonyStack = () => {  return (<Stack.Navigator><Stack.Screen name="Matrimony" component={MatrimonyTab} /><Stack.Screen name="GroomDetail" component={GroomDetail} /></Stack.Navigator>  );};

How to import module according platform

$
0
0

I want import a module according platform.

For example:

import MapViewIOS from 'react-native-map-clustering'import MapViewAndroid from 'react-native-maps'const MapView = Platform.select({  ios: MapViewIOS,  android: MapViewAndroid,})

Error:

JSX element type 'MapView' does not have any construct or callsignatures.ts(2604)


Lerna with Yarn, TypeScript and React Native: Cannot find module '@project/common' or its corresponding type declarations.ts(2307)

$
0
0

The project uses Yarn, React Native, Lerna and Typescript. It is structured as a monorepo

Here is the structure:

project|- packages   | - mobile       | - src       | - packages.json       | - tsconfig.json   | - cloud-functions       | - src       | - packages.json       | - tsconfig.json   | - common1       | - lib       | - src       | - packages.json       | - tsconfig.json   | - common2       | - lib       | - src       | - packages.json       | - tsconfig.json| - packages.json| - tsconfig.json| - lerna.json

lerna.json looks like this:

{"packages": ["packages/*"  ],"npmClient": "yarn","version": "0.0.7",}

The root packages.json looks like this:

{"name": "project","private": true,"scripts": {    ...  },"devDependencies": {"@types/node": "^14.0.27","lerna": "^3.22.1","ts-node": "^8.10.2","typescript": "^3.9.7"  }}

The root tsconfig.json looks like this:

{"compilerOptions": {"noImplicitAny": true,"noUnusedLocals": true,"removeComments": true,"noLib": false,"emitDecoratorMetadata": true,"experimentalDecorators": true,"sourceMap": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"resolveJsonModule": true,"baseUrl": "./","paths": {"@project/common1": ["packages/common1/lib"],"@project/common2": ["packages/common2/lib"],"@project/mobile": ["packages/mobile/src"],"@project/cloud-functions": ["packages/cloud-functions/src"],    }  },"exclude": ["node_modules", "**/*.spec.ts", "**/__tests__/*", "babel.config.js", "metro.config.js", "jest.config.js"]}

The typical packages/common/packages.json looks like this:

{"name": "@project/common1","version": "0.0.7","main": "lib/index.js","types": "lib/index.d.ts","files": ["lib/**/*"  ],"private": true,"devDependencies": {"@project/common2": "latest", //for common1 only"@types/node": "^14.0.27","ts-node": "^8.10.2","typescript": "^3.9.7"  },"dependencies": {    ...  }}

The typical packages/common/tsconfig.json looks like this:

{"extends": "../../tsconfig.json","compilerOptions": {"module": "commonjs","outDir": "lib","strict": true,"target": "es6"  },"compileOnSave": true,"include": ["src"]}

The React Native file packages/mobile/packages.json looks like this:

{"name": "@project/mobile","version": "0.0.7","private": true,"dependencies": {"@project/common1": "latest","@project/common2": "latest",        ...    },"devDependencies": {        ..."ts-node": "^8.10.2","typescript": "^3.8.3"    },}

I first ran into:

lerna ERR! yarn install --mutex network:42424 --non-interactive stderr:warning Waiting for the other yarn instance to finish (19560)warning Waiting for the other yarn instance to finish (21568)error An unexpected error occurred: "https://registry.yarnpkg.com/@project%2fcommon1: Not found".

Obviously Yarn is trying to pull the dependencies from its packages registery. This fails.

Then I tried to remove the references to @project/common1 and @project/common2 in the dependencies of the packages.

In the source, VS Code underline the imports in red and prints:

Cannot find module '@project/common1' or its corresponding type declarations.ts(2307)

I also tried to use Yarn Workspace, yet I ran into modules hoisting issues with React Native. I did not want create a list of all possibly incompatible package, since it seems to be difficult to maintain.

"workspaces": {"nohoist": ["react-native", "react-native/**", "@react-native-community/checkbox", "@react-navigation/native"]}

Is there a simple solution ?

Or is it simpler for this use case to abandon Lerna and use GitHub based common repositories?

Keyboard constantly closes with each typed on input child

$
0
0

Every time I type something it closes the keyboard I've tried using onChangeText and onChange but nothing has changed

Parent component

const [searchText, setSearchText] = useState('');function handleSearchTextChange(e: NativeSyntheticEvent<TextInputChangeEventData>) {  setSearchText(e.nativeEvent.text);}<PageHeader   hasSearch={true}   isLogout={true}   searchTextInput={searchText}   onSearchTextChange={handleSearchTextChange}/>

child component

<TextInput          style={{width: 250}}          autoCorrect={true}          placeholder="Pesquisar..."          value={searchTextInput}          onChange={onSearchTextChange}        />

react-navigation navigation hook type

$
0
0

I am using this hook from react-navigation and instead of calling the hook again in different components, I want to pass navigation as a prop.

const navigation = useNavigation();...<MyButton     resetLocation={resetLocation}     navigation={navigation}  /> 

But I am unable to figure out the "type" for this navigation prop that I should pass into my MyButton component.

type MyButtonProps = {  resetLocation: (locationToReset: string) => void;  navigation: any;};export const MyButton: React.FunctionComponent<MyButtonProps> = ({  resetLocation,  navigation,

What should I replace navigation: any; with?

React native, I'm not able to navigate between screens

$
0
0

I am following the react navigation documentation. I did all the installations.I'm using react native expo in the latest version (0.63).When I create a screen or create a function from within app.tsx, I have the following problem.

enter image description here

Losing data after connecting the bluetooth module

$
0
0

Objective

I am trying to return data from the BlueTooth device after connected because to use the read and write function, need some data.Example data name, overflowServiceUUIDs, solicitedServiceUUIDs, mtu, rssi... and many others. Because if I want to read or write I need some attributes. I am using the library react-native-ble-plx.

What is happening?

After the device connected I lost some values.

Important

type DeviceState = {  connected: boolean;  services: Service[];  device: Device | null;  characteristics: Record<string, Characteristic[]>;};const INITIAL_DEVICE_STATE = {  connected: false,  services: [],  device: null,  characteristics: {},};
const [adapterState, setAdapterState] = useState(false);const [bleDevices, setBleDevices] = useState<Device[]>([]);const [isScanning, setIsScanning] = useState(false);const [connectedDevice, setConnectedDevice] = useState<DeviceState>(    INITIAL_DEVICE_STATE,);# The state isScaning is used to be if we are scanning devices.# The connectedDevice state will be the connected device.

The sequence functions

toggleScanDevices()

Will push all devices to the bleDevices state.

const toggleScanDevices = () => {    setIsScanning(true);    setBleDevices([]);    bleManager.startDeviceScan(null, {}, (bleError, device) => {      if (device && _.findIndex(bleDevices, { id: device.id }) < 0) {        bleDevices.push(device);        setBleDevices(bleDevices);      }    });    setTimeout(() => {      setIsScanning(false);      bleManager.stopDeviceScan();    }, 5000);  };

toggleConnectDevice(device.name)

const toggleConnectDevice = (name: string) => async () => {    if (!connectedDevice.device) {      await connectDevice(name);    } else {      const { device } = connectedDevice;      if (!device) return;      await device.cancelConnection();      if (!(await device.isConnected())) {        setConnectedDevice(INITIAL_DEVICE_STATE);      }    }  };

connectDevice(name)

const connectDevice = async (name: string) => {    let device = findDeviceWhereNameContains(name);    if (device === null) {      setConnectedDevice(INITIAL_DEVICE_STATE);      return false;    }    let isConnected = await device.isConnected();    if (!isConnected) {      /* Testar aqui */      device = await bleManager.connectToDevice(device.id);      isConnected = await device.isConnected();    }    device = await device.discoverAllServicesAndCharacteristics();    device.onDisconnected((error, device) => {      setConnectedDevice(INITIAL_DEVICE_STATE);    });    const services = await device.services();    const characteristics: Record<string, Characteristic[]> = {};    const descriptors = {};    _.forEach(services, async service => {      const deviceCharacteristics = await device?.characteristicsForService(        service.uuid,      );      characteristics[service.uuid] = deviceCharacteristics || [];    });    setConnectedDevice(state => ({      ...state,      services,      characteristics,      device,    }));    const newDevice = { ...connectedDevice, device };    setConnectedDevice(newDevice);    console.log('não atualizado', connectedDevice);    console.log('novo valor', newDevice);  };

findDeviceWhereNameContains(name)

const findDeviceWhereNameContains = (name: string) => {    const device = bleDevices.find(item => String(item.name).includes(name));    if (device !== undefined) {      return device;    }    return null;  };

Inside the connectDevice function I have a let device that receive the value about the findDeviceWhereNameContains, if I log this variable device I receive many data very important, but I'm not connected yet. So when I verify about the if (!isConnected) here I will connect, and after this, inside out this if when I log the device again I lost some values.

The log before connect

The data before the connection

The log after connect

Device {overflowServiceUUIDs: null, solicitedServiceUUIDs: null, localName: null, isConnectable: null, txPowerLevel: null, …}overflowServiceUUIDs: nullsolicitedServiceUUIDs: nulllocalName: nullisConnectable: nulltxPowerLevel: nullserviceUUIDs: nullserviceData: nullmtu: nullname: "MLT-BT05"manufacturerData: nullrssi: nullid: "88:25:83:F0:30:BC"
Viewing all 6214 articles
Browse latest View live


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