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

Focusing the next input after reaching the max length React Native

$
0
0

I want to be able to move the focus from one input onto the next after the user has entered 2 numbers in the input box. Instead of the user manually clicking the next field I'd like the focus to switch there automatically.

Below is how I've currently implemented my two input fields.

I've tried the things mentioned here using refs but doesn't seem to work at all https://www.codegrepper.com/code-examples/csharp/react+native+textinput+focus

<Controller                control={form.control}                defaultValue={initialMonthValue}                name={monthName}                render={({ onChange, onBlur, value }) =><Input                        containerStyle={{ width:80 }}                        editable={!isSubmitting}                        autoCapitalize="none"                        numberOfLines={1}                        multiline={false}                        keyboardType='number-pad'                        placeholder="MM"                        maxLength={2}                         placeholderTextColor={Colors.Grey}                        onChangeText={onChange}                        onBlur={onBlur}                        secureTextEntry={false}                        invalid={!!monthError}                        value={value} />}            /><Slash text="/" /><Controller                control={form.control}                defaultValue={initialYearValue}                name={yearName}                render={({ onChange, onBlur, value }) =><Input                        containerStyle={{ width:80 }}                        editable={!isSubmitting}                        autoCapitalize="none"                        numberOfLines={1}                        multiline={false}                        keyboardType='number-pad'                        placeholder="YY"                        placeholderTextColor={Colors.Grey}                        onChangeText={onChange}                        onBlur={onBlur}                        secureTextEntry={false}                        invalid={!!yearError}                        value={value} />}            />

Loading data from AsyncStorage to FlatList after reloading app

$
0
0

I've got a question, how can I load data from asyncStorage to my FlatList after I reload the app?Here is my screen, where I have the data, FlatList and asyncStorage:

import { StatusBar } from 'expo-status-bar';import React, {useState, useEffect} from 'react';import {   StyleSheet,   Text,  View,   Button,   FlatList,  Alert,} from 'react-native';import AsyncStorage  from '@react-native-community/async-storage';import GoalItem from'../components/Goalitem';import colors from '../constants/colors';type Props={  navigation:any}const MainScreen = (props:Props) =>{  const input: string = props.navigation.getParam('input');  const [products, setProducts]  = useState<any>([]);  const storeData = async(id:string, value:string) =>{    try{      const product ={        productId: id,        productName: value      }      const existing_products:any = await AsyncStorage.getItem('stored_products');      let new_product:any = JSON.parse(existing_products);      if(!new_product)      {        new_product = [];      }      new_product.push(product);      await AsyncStorage.setItem('stored_products', JSON.stringify(new_product));      console.log(new_product);     }    catch (err){        alert(err);    }};useEffect( () => {  let douledvalue:string = '';  let id:string = Math.random().toString();  if(input !== undefined && douledvalue !== input)    setProducts([...products,{id: id, value: input}]);  if(input !== null && input !== undefined)   {  storeData(id ,input);  }}, [input])  function removeGoalHandler(goalId:any):void  {    setProducts((courseGoals: any[]) =>     {      return courseGoals.filter((goal:any) => goal.id !== goalId);    });  };  function deleteListAlert():void  {    if(products.length >0)    {      Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?',        [{text: 'Tak', style: 'destructive', onPress: deleteList},         {text: 'Nie', style: 'cancel'}]);    }    else{      Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.',        [{text: 'Powrót', style: 'cancel'}]);    }  }  function deleteList()  {    setProducts('');  }  return (<View style = {styles.screen}>    <FlatList style = {styles.flatListPosition}        keyExtractor={(item, index) => item.id}         data = {products}        renderItem ={itemData => (<GoalItem           id = {itemData.item.id}           onDelete = {removeGoalHandler}           title = {itemData.item.value}           />        )}      /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {'mediumaquamarine'} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {'mediumaquamarine'} title="+" onPress = {() => {            props.navigation.navigate('Adding')          }}/></View></View></View>  );}MainScreen.navigationOptions = {  headerTitle: 'Lista zakupów',  headerStyle:{    backgroundColor: 'mediumaquamarine'  },  headerTintColor: 'white'};const styles = StyleSheet.create({  screen:{   flex:1,   backgroundColor: 'white',  },  button:{    width: 40,  },  button1:{    width: 90,  },  buttonPosition:{    padding:15,    alignItems: 'stretch',    justifyContent: 'space-between',    flexDirection:'row',    //backgroundColor: 'transparent'  },  flatListPosition:{    padding: 8,  }});export default MainScreen;

Here I'm adding data to async:

const storeData = async(id:string, value:string) =>{    try{      const product ={        productId: id,        productName: value      }      const existing_products:any = await AsyncStorage.getItem('stored_products');      let new_product:any = JSON.parse(existing_products);      if(!new_product)      {        new_product = [];      }      new_product.push(product);      await AsyncStorage.setItem('stored_products', JSON.stringify(new_product));      console.log(new_product);     }    catch (err){        alert(err);    }};

I don't know if it's possible but I must keep the state of the list in products:

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

But after reloading app, upload the data from asyncStorage to FlatList (it's not my idea, i've got this in requirements :D)

How to call react function from external JavaScript file

$
0
0

I have read this post [ https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/ ]

But I don't understand.

that is not working on my source code.

it's my tsx file

declare global {  interface Window {    fn_test(): void;    childComponent: HTMLDivElement; <-- what the... ref type????   }}export default function Contact(): React.ReactElement {....  function file_input_html( i:number ): React.ReactElement {    return (<form id={`frm_write_file_${i}`} .... </form>     )  }....  return (<div ref={(childComponent) => {window.childComponent = childComponent}}>       ....)

it's my external javascript file

function fn_test(){    window.childComponent.file_input_html(3)    var element = document.getElementById("ifrm_write_file");    // element.value = "mystyle";}

How can i call file_input_html function?

plase help me ...

Unhandled JS Exception: Requiring unknown module "9"

$
0
0

So I'm trying to set up the navigation for a log in screen and I've tried relinking dependecies and installing packages all over again and I've only worked on two files. I am working on MacOS and simulating on iOS 13.5.

This is the complete error when trying to simulate.

App.js

import React, { Component } from 'react'import {  StyleSheet,  View} from 'react-native'import Mystack from './navigators/StackNavigator'export default class App extends Component {render() {  return (<NavigationContainer><Mystack/></NavigationContainer> ) }} const styles = StyleSheet.create({  container: {}, })

and StackNavigator.js

import * as React from 'react';import { createStackNavigator} from '@react-navigation/stack';import { NavigationContainer } from '@react-navigation/native';import LogIn from './src/components/LogIn.js'import SignUp from './src/components/SignUp.js'import Dashboard from './src/components/Dashboard.js'const Stack = createStackNavigator();function Mystack() {     return(<Stack.Navigator initialRouteName = "LogIn"         screenOptions = {{         headerTitleAlign: 'center',         HeaderStyle: {             backgroundColor: "#FFF700",         },           headerTintColor: '#FFF',           headerTitleStyle: {               fontWeight: 'bold',         },        }}><Stack.Screen name = "LogIn"        component = {LogIn}        options = {{           title: 'LogIn',           headerShown: false        }}/><Stack.Screen name = "SignUp"         component = {SignUp}         options = {{             title: 'SignUp',             headerShown: false        }}/><Stack.Screen name = "Dashboard"        component = {Dashboard}        options = {{            title: 'Dashboard'        }        }/></Stack.Navigator>       )       }      export default Mystack;

Is there any way to prevent screenshot in React Native IOS version 0.63?

$
0
0

Is it possible to disable screenshots in React Native app for a specific page in IOS?

I have already used the RN AppState feature to hide the content when the App is inactive or in the background state but this feature does not seem to work to prevent screenshots.

Any help would be appreciated. Thanks in advance!

React Node node not found while testing FaC with Jest and Enzyme

$
0
0

I'm building an app in React Native. We recently started using TypeScript in the app and my task is to migrate the unit tests. There is one test that is miracously failing.

The app has a <LoginForm /> that uses Formik.

//... importsexport interface FormValues {  email: string;  password: string;}export interface Props {  navigation: NavigationScreenProp<any, any>;}export default class LoginForm extends Component<Props, object> {  handleSubmit = (values: FormValues, formikBag: FormikActions<FormValues>) => {    // ... api calls and stuff  };  renderForm = ({    values,    handleSubmit,    setFieldValue,    touched,    errors,    setFieldTouched,    isValid,    isSubmitting  }: FormikProps<FormValues>) => (<View style={styles.container}>      // ... two inputs and a button</View>  );  render() {    return (<Formik        initialValues={{ email: "", password: "" }}        onSubmit={(values: FormValues, formikBag: FormikActions<FormValues>) =>          this.handleSubmit(values, formikBag)        }        validationSchema={<some_schema>}        render={(formikBag: FormikProps<FormValues>) => this.renderForm(formikBag)}      />    );  }}

This is how the unit test looks for the Function as Child renderForm():

describe("renderForm", () => {  let formWrapper: ShallowWrapper;  beforeEach(() => {    let formikBagMock: any = {      values: { email: "Test Email", password: "testpassword" },      handleSubmit: jest.fn(),      setFieldValue: jest.fn(),      errors: { email: "Test error", password: "" },      touched: { email: true, password: false },      setFieldTouched: jest.fn(),      isValid: false,      isSubmitting: false    };    formWrapper = shallow(wrapper.instance().renderForm(formikBagMock));  });  it("should render a <View />", () => {    expect(formWrapper.find("View")).toHaveLength(1);  });  it("should render two <Input />", () => {    expect(formWrapper.find("Input")).toHaveLength(2);  });  it("should render a <Button />", () => {    expect(formWrapper.find("Button")).toHaveLength(1);  });  describe("styling", () => {    it("should give the <View /> the 'container' style", () => {      expect(formWrapper.find(View).prop("style")).toEqual(styles.container);    });  });});

The problem is that, while this test was passing in .js it is failing in .tsx.

The error thrown looks like this:● LoginForm › rendering › renderForm › should render a <Button />    expect(received).toHaveLength(length)    Expected value to have length:      1    Received:      {Symbol(enzyme.__root__): {Symbol(enzyme.__root__): [Circular], Symbol(enzyme.__unrendered__): <Component style={{"alignItems": "center", "flex": 1, "justifyContent": "space-evenly"}}><Input autoCapitalize="none" editable={true} errorMessage="Test error" keyboardType="email-address" onBlur={[Function onBlur]} onChangeText={[Function onChangeText]} placeholder="Email address" value="Test Email" /><Input autoCapitalize="none" editable={true} onBlur={[Function onBlur]} onChangeText={[Function onChangeText]} placeholder="Password" secureTextEntry={true} value="testpassword" /><Button TouchableComponent={[Function anonymous]} buttonStyle={{"backgroundColor": "#DC4F19"}} clear={false} containerStyle={{"paddingVertical": 5, "width": "33%"}} disabled={true} disabledStyle={{"backgroundColor": "#DC4F19", "opacity": 0.3}} disabledTitleStyle={{"color": "white"}} iconRight={false} loading={false} loadingProps={{"color": "white", "size": "large"}} onPress={[Function mockConstructor]} raised={false} title="Log In" titleStyle={{"color": "white"}} /></Component>, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function batchedUpdates], "getNode": [Function getNode], "render": [Function render], "simulateError": [Function simulateError], "simulateEvent": [Function simulateEvent], "unmount": [Function unmount]}, Symbol(enzyme.__node__): {"instance": null, "key": undefined, "nodeType": "function", "props": {"children": [Function anonymous]}, "ref": null, "rendered": [Function anonymous], "type": {"$$typeof": Symbol(react.context), "Consumer": [Circular], "Provider": {"$$typeof": Symbol(react.provider), "_context": [Circular]}, "_calculateChangedBits": null, "_currentRenderer": null, "_currentRenderer2": null, "_currentValue": false, "_currentValue2": false, "unstable_read": [Function bound readContext]}}, Symbol(enzyme.__nodes__): [{"instance": null, "key": undefined, "nodeType": "function", "props": {"children": [Function anonymous]}, "ref": null, "rendered": [Function anonymous], "type": {"$$typeof": Symbol(react.context), "Consumer": [Circular], "Provider": {"$$typeof": Symbol(react.provider), "_context": [Circular]}, "_calculateChangedBits": null, "_currentRenderer": null, "_currentRenderer2": null, "_currentValue": false, "_currentValue2": false, "unstable_read": [Function bound readContext]}}], Symbol(enzyme.__options__): {"adapter": {"options": {"enableComponentDidUpdateOnSetState": true, "lifecycles": {"componentDidUpdate": {"onSetState": true}, "getDerivedStateFromProps": true, "getSnapshotBeforeUpdate": true, "setState": {"skipsComponentDidUpdateOnNullish": true}}}}, "attachTo": undefined, "hydrateIn": undefined}}, Symbol(enzyme.__unrendered__): null, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function batchedUpdates], "getNode": [Function getNode], "render": [Function render], "simulateError": [Function simulateError], "simulateEvent": [Function simulateEvent], "unmount": [Function unmount]}, Symbol(enzyme.__node__): undefined, Symbol(enzyme.__nodes__): [], Symbol(enzyme.__options__): {"adapter": {"options": {"enableComponentDidUpdateOnSetState": true, "lifecycles": {"componentDidUpdate": {"onSetState": true}, "getDerivedStateFromProps": true, "getSnapshotBeforeUpdate": true, "setState": {"skipsComponentDidUpdateOnNullish": true}}}}, "attachTo": undefined, "hydrateIn": undefined}}    received.length:      0      61 |      62 |       it("should render a <Button />", () => {> 63 |         expect(formWrapper.find("Button")).toHaveLength(1);         |                                            ^      64 |       });      65 |      66 |       describe("styling", () => {

How can it be, that Enzyme suddenly does not find the node anymore? I even tried importing the components View, Button and Input directly and passing that to find() instead of the strings, but it doesn't change anything. What am I doing wrong?

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

$
0
0

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

useEffect() :

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

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

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

Tanks

React Native: which pattern is best for opening and closing Realm instance?

$
0
0

I need to persist lots of different data objects (nested, with relationships) that are used across several components with Realm (10.1.3) for a react native project (0.63.3).

My goal is to have a class that provides an API with read and write operations on Realm for all other modules, screens and so on. However I have trouble finding the right pattern for it.

Idea 1: Implement all operations in one place, open and close Realms each time

Write-Operations run smoothly:

export class RealmProviderSample {    static asnyc writeObject(object:ObjectType) {       const realm = await Realm.open(config);           realm.write(() => {                realm.create("ObjectType", object);           });        realm.close();     }  // ...}

However reading an object and closing the realm leads to Errors as the data cannot be used anymore when the realm is closed. I got stuck on trying to clone the realm object (I need a deep copy), but the clone is always empty. This seems to be a known problem: issue 2805, issue 1074

import { cloneDeep } from 'lodash';export class RealmProviderSample {    // ...    static async readObject() : Promise<Object> {        let object:Object = {}        const realm = await Realm.open(config)        const tmpReferencedObject = <Object> realm.objects("Object")         object = cloneDeep(tmpReferencedObject)          console.log(object) // object is empty {}         realm.close();        return tmpReferencedObject // Error "invalidated results" when using the returned object, because realm was closed    } }

This approach only works when the copy problem is solved (there is a solution for Swift. Encode in JSON and then Decode back is not working either, because the Realm object has relations (TypeError JSON.stringify cannot serialize cyclic structures)

Idea 2: Implement all operations in one place, manage a global realm instance

An alternative solution would be to have a global realm instance that is opened on the first use and closed, when the application is send to the background.

var realm:Realmexport class RealmProviderSample {    static asnyc writeObject(object:ObjectType) {        if (!realm || realm.isClosed) {            realm = await Realm.open(config);        }        realm.write(() => {            realm.create("ObjectType", object);        });    }    static async readObject() : Promise<Object> {        if (!realm || realm.isClosed) {            realm = await Realm.open(config);        }        return <Object> realm.objects("Object")     }    // call this when application goes to background?    static closeRealmIfOpen(){        if (realm && !realm.isClosed) {            realm.close();        }    }}

To me it is not clear whether it is a good idea to leave the realm open. In the docs it is stated that a realm should always be closed when not used.

Idea 3: Implement each operation where it is used, manage each realm separately

This the approach I can see in all the tutorials, but I have the feeling that it doesn't scale. Also most samples don't close the realms.

class MyScreen extends React.Component {    realm: Realm;    // constructor...    componentDidMount() {        this.realm = new Realm(config);        this.realm.write(() => {            this.realm.create("ObjectType", object);        });    }    componentWillUnmount() {        this.realm.close()    }    // render ...}

If data is used across several screens and components (some sub-data passed via Props) it might be difficult to close the instance safely.

I prefer idea one - but it doesn't work without the deep copy of a realm object. Did anyone solve this problem? Which pattern do you use and does it scale?


Jest cannot find module @env React Native

$
0
0

I'm currently facing some problem I'm using in my react native app https://github.com/goatandsheep/react-native-dotenv for handling .env.

Error => Cannot find module '@env' from 'src/api/api.ts'

I'm testing currently my redux saga to call the api endpoint:

import axios from 'axios';import {API_URL} from '@env';export default axios.create({  baseURL: API_URL,  responseType: 'json',});

API Endpoint

export const sendCheckNumber = async (  phoneNumber: string,): Promise<AuthenticationTO> => {  const response = await axios.get<AuthenticationTO>(    `SendCheckNumber/${phoneNumber}`,  );  return response.data;};

I'm using ts-jest package.json. I saw in the docs its possible to include bable in ts-jest because I'm using bable to import the 'module:react-native-dotenv', as plugin. I thought that will already solve my problem but unfortunately it still fails. Maybe someone of you have some suggestion what could cause this error.

Thank you!!!

package.json

"jest": {"preset": "react-native","transform": {"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js","\\.(ts|tsx)$": "ts-jest"    },"globals": {"ts-jest": {"babelConfig": "babel.config.js","tsConfig": "tsconfig.jest.json"      }    },"moduleFileExtensions": ["ts","tsx","js"    ],"modulePaths": ["<rootDir>/src"    ],"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"  }

How can export a default realm configuration function without getting an error Realm

$
0
0

I'm trying to export useRealm which will enable me to use in other files, e.g redux-thunk.The code i wrote:

import Realm from "realm";import { getRealmApp } from "../functions/realmConfig";import { ItemSchema } from "./itemSchema";const app = getRealmApp();const user = Realm.User;const useConfig = {  schema: [ItemSchema], //other schema will be added in the future  sync: {    user: user.prototype,    partitionValue: user.name,  },};export const useRealm = Realm.open({  schema: [ItemSchema],  sync: {    user: user.prototype,    partitionValue: app.currentUser?.id!,    error: (e) => {      console.log(e);    },  },});

But this configuration tends to throw an error:

Uncaught Error: Invalid object. No _instance member    at Function.open (/Users/newuser/workspace/programming/desktop/numberz/node_modules/realm/lib/extensions.js:183)    at eval (index.ts?77fd:17)    at Object../src/realm/index.ts (renderer.js:5394)    at __webpack_require__ (renderer.js:791)    at fn (renderer.js:102)    at eval (index.ts?788b:3)    at Object../src/redux/testReducer/index.ts (renderer.js:5427)    at __webpack_require__ (renderer.js:791)    at fn (renderer.js:102)    at eval (index.ts?76a6:9)

I've tried example but they were using react context, which i can not use as i'm building a big app thats way to complex for context api

Cannot read property 'id' of null From Realm database

$
0
0

I'm getting an error when I want to export a default realm configuration useRealm so that I will be able to use it other files

import Realm from "realm";import { getRealmApp } from "../functions/realmConfig";import { ItemSchema } from "./itemSchema";export const app = getRealmApp();export const useRealmApp = getRealmApp();export const user = useRealmApp.currentUser;export const partitionValue = useRealmApp.currentUser.id;export const config = {  schema: [ItemSchema], //other schema will be added in the future  sync: {    user: user,    partitionValue: partitionValue, //app.currentUser.id,  },};export const useRealm = new Realm(config);

expected results is, if the user is not logged in it should show a login screen. But it throws this error and doesn't give me a chance to log in:

index.ts?77fd:9 Uncaught TypeError: Cannot read property 'id' of null    at eval (index.ts?77fd:9)    at Object../src/realm/index.ts (renderer.js:5394)    at __webpack_require__ (renderer.js:791)    at fn (renderer.js:102)    at eval (testIndex.tsx?956d:10)    at Object../testIndex.tsx (renderer.js:5438)    at __webpack_require__ (renderer.js:791)    at fn (renderer.js:102)    at eval (App.tsx?d35d:4)

JSON response cannot extract variables

$
0
0

Brand new to react-native and typescript!I'm have a bit of trouble extracting JSON response. I was to extract the response and put it into a class as shown below.

Here is the request code

    let notifications: INotification[]    notifications = (await Requests.GET('notification/user/test-user-1', accessToken));

Here is the class

      export interface INotification {          id: string;          senderId: string;          receiverId: string;          text: string;          isSeen: boolean;          type: string;          timestamp: string;      }

Here is the Postman response

{"notifications": [        {"pk": "user-1","sk": "notification1234","entity": "notification","id": "id number","senderId": "test-user-2","receiverId": "test-user-1","text": "Test notifications","isSeen": false,"type": 2        }    ]}

Here is response from the console

  { notifications:        [ { pk: 'user#test-user-1',           sk: 'notification1234',           entity: 'notification',           id: 'id number',           senderId: 'test-user-2',           receiverId: 'test-user-1',           text: 'Test notifications',           isSeen: false,           type: 2 } ] }

I want to be able to write out:

console.log("TEXT: ",notifications[0].text )

And get the response of : "Text: Test notifications"

Any help welcome!

how to change button style by props? [closed]

$
0
0

I want to pass a theme as a parameter to my component button but the style is not being applied

My Component:

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {  theme: string}const Button: React.FC<ButtonProps> = ({ children, theme }) => {  return (<Container type="button" theme={theme}>      {children}</Container>  )}

Styles file:

const theme = {  blue: {    default: '#3f51b5',    hover: '#283593'  },  pink: {    default: '#e91e63',    hover: '#ad1457'  }}export const Container = styled.button`  display: flex;  justify-content: center;  background: ${props => theme[props.theme].defautl};

My index:

<Button theme="pink">Click</Button>

does anyone know where the error is or how can i do this?

Use typescript in proton native

$
0
0

I am using proton native and I added typescript dependencies to package.json but proton native doesn't recognize it throw a syntax error.Can anyone help me to add typescript to proton native?Note that it should be included in the fast refresh, too.

Why is result undefined

$
0
0

I am trying to access a user's details from a get Request but I cannot figure out for the life of me why the I can only log some of the response results...

Here is the request:

let user  = (await Requests.GET("/user/test-user-3", accesToken3)).user;

Here is the response in the console:

 {  pk: 'user#test-user-3',          sk: 'user#test-user-3',          entity: 'user',          id: 'test-user-2',          companyId: 'test-company',          fName: 'Test',          lName: 'User 2',          email: 'test2@gmail.com',          isComplete: true,          weight: 80,          height: 160,          dob: '15/09/1998',          fitnessTrackers: [],          department: 'Development',          location: 'USA',          coins: 100,          gender: 'male'}

Here is the what I log:

    console.log("COINS: ", user.coins);

And I get a result of:

'COINS: ', 100

But when I try to log out the user's fname like:

    console.log("Name: ", user.fname);

I get a result of undefined

I really just don't understand what the problem is here at all please help!!


Invalid attempt to spread non-iterable instance. (App which worked fine)

$
0
0

I've got a question about an error below. Everything worked fine im my app, I added sth about 5 lines, this error appears, then I remove that lines but the error didn't disappear. Maybe somebody can help me because I dont' have any ideas what's wrong with this code especially that it worked fine, thanks :)

import { StatusBar } from 'expo-status-bar';import React, {useState, useEffect} from 'react';import {   StyleSheet,   Text,  View,   Button,   FlatList,  Alert,} from 'react-native';import AsyncStorage  from '@react-native-community/async-storage';import GoalItem from'../components/Goalitem';import colors from '../constants/colors';type Props={  navigation:any}type Product ={  productId:string,  productName:string}const MainScreen = (props:Props) =>{  const getStoredData = async() =>{    try{      const retrieved_prod:any = await AsyncStorage.getItem('stored_products');      let prod:Product[] = JSON.parse(retrieved_prod);      //console.log(prod);      return prod;    }    catch(err){      alert(err);    }  }  const input: string = props.navigation.getParam('input');  const [products, setProducts]  = useState<any>([]);  useEffect(()=>{    getStoredData().then((prod) =>{      setProducts(prod);    });  },[])  useEffect( () => {    let douledvalue:string = '';    let id:string = Math.random().toString();    if(input !== undefined && douledvalue !== input && input !== null)      addProduct({productId:id, productName:input});  }, [input])  function addProduct(prod:Product)  {    setProducts([...products,prod]);    storeData(prod);  }  const storeData = async(prod:Product) =>{    try{      const existing_products:any = await AsyncStorage.getItem('stored_products');      let new_product:Product[] = JSON.parse(existing_products);      if(!new_product)      {        new_product = [];      }      new_product.push(prod);      await AsyncStorage.setItem('stored_products', JSON.stringify(new_product));    }    catch (err){        alert(err);    }};const cleanStorage = async() =>{  AsyncStorage.clear();}const deleteSingleItem = async(Id:string)=>{try{  let prodcuct:any= await AsyncStorage.getItem('stored_products');  let productsArray:Product[] = JSON.parse(prodcuct);  let productsWithDeleted = productsArray.filter((item:Product) => item.productId != Id);  AsyncStorage.setItem('stored_products', JSON.stringify(productsWithDeleted));}catch(err)  {console.log(err)}}  function removeGoalHandler(Id:string):void  {    setProducts((products: Product[]) =>     {      return products.filter((item:Product) => item.productId !== Id);    });    deleteSingleItem(Id);  };  function deleteListAlert():void  {    if(products.length >0)    {      Alert.alert('Lista zostanie wyczyszczona!','Czy aby na pewno chcesz wyczyścić liste?',        [{text: 'Tak', style: 'destructive', onPress: deleteList},         {text: 'Nie', style: 'cancel'}]);    }    else{      Alert.alert('Lista jest pusta.','W liście nie ma żadnych przedmiotów.',        [{text: 'Powrót', style: 'cancel'}]);    }  }  function deleteList()  {    setProducts('');    cleanStorage();  }  return (<View style = {styles.screen}>    <FlatList style = {styles.flatListPosition}        keyExtractor={({productId}) => productId}         data = {products}        renderItem ={({item: {productId, productName}}) => (<GoalItem           id = {productId}           onDelete = {removeGoalHandler}           title = {productName}           />        )}      /><View style = {styles.buttonPosition}><View style = {styles.button1}><Button color = {'mediumaquamarine'} title = "WYCZYŚĆ" onPress={deleteListAlert}/></View><View style = {styles.button}><Button color = {'mediumaquamarine'} title="+" onPress = {() => {            props.navigation.navigate('Adding')          }}/></View></View></View>  );}MainScreen.navigationOptions = {  headerTitle: 'Lista zakupów',  headerStyle:{    backgroundColor: 'mediumaquamarine'  },  headerTintColor: 'white'};const styles = StyleSheet.create({  screen:{   flex:1,   backgroundColor: 'white',  },  button:{    width: 40,  },  button1:{    width: 90,  },  buttonPosition:{    padding:15,    alignItems: 'stretch',    justifyContent: 'space-between',    flexDirection:'row',  },  flatListPosition:{    padding: 8,  }});export default MainScreen;

React native webview can not open links on android

$
0
0

React native webview component can not open links on Android, but on IOS it works fine, without any troubles. Nothing has happening on Android, after the pressing, no any errors. At the same time i tried to open links with react native hyperlink, and it works fine. Can you tell me please how can i solve it?

const IS_IOS = Platform.OS === 'ios';const script = `;(function() {var wrapper = document.createElement("div");wrapper.id = "height-wrapper";while (document.body.firstChild) {    wrapper.appendChild(document.body.firstChild);}document.body.appendChild(wrapper);var i = 0;function click(e) {  e.preventDefault();  window.postMessage(click, '*');};function updateHeight() {    document.title = wrapper.scrollHeight;    window.location.hash = ++i;}function linkProcessed() {    var links = document.getElementsByTagName('a');    for (var i = 0; i < links.length; i++) {        links[i].onclick = function (e) {            e.preventDefault();            window.ReactNativeWebView.postMessage(e.currentTarget.getAttribute("href"), '*');        }    }    var links = document.getElementsByTagName('img');    for (var i = 0; i < links.length; i++) {        links[i].onclick = function (e) {            e.preventDefault();            window.ReactNativeWebView.postMessage(e.currentTarget.getAttribute("src"), '*');        }    }}updateHeight();setTimeout(linkProcessed, 1000);window.addEventListener("load", function() {    updateHeight();    setTimeout(updateHeight, 1000);});window.addEventListener("resize", updateHeight);}());`;const postMessage = `(function() {    var originalPostMessage = window.postMessage;    var patchedPostMessage = function(message, targetOrigin, transfer) {        originalPostMessage(message, targetOrigin, transfer);    };    patchedPostMessage.toString = function() {        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');    };    window.postMessage = patchedPostMessage;})();`;const style = `<style>body, html, #height-wrapper {    margin: 0;    padding: 0;}#height-wrapper {    position: absolute;    top: 0;    left: 0;    right: 0;}</style><script>${script}</script>`;const textStyleToCss = (textStyle: StyleProp<TextStyle>, styles?: StyleProp<ViewStyle>): string => {  if (!textStyle) {    return '';  }  const {    fontSize,    fontFamily,    fontUrl,    lineHeight,    letterSpacing,    color,  } = StyleSheet.flatten(textStyle) as any;  const {    backgroundColor,  } = StyleSheet.flatten(styles) as any;  const css = IS_IOS ?    `<style type="text/css">@font-face {font-family: MyFont; font-style: normal;    font-weight: 400; src: local('${fontFamily}'), url('${fontUrl}');}body,* {    font-family: MyFont; font-size: ${fontSize}pt;text-align: left; line-height: ${lineHeight}pt; letter-spacing: ${letterSpacing}pt; color: ${color};    background-color: ${backgroundColor};}img{height: auto;max-width: 100%;}iframe {height: auto;max-width: 100%;}div{height: auto;max-width: 100%;}</style>` :    `<style type="text/css">@font-face {font-family: MyFont; font-style: normal;      font-weight: 400; src: url("${fontUrl}");}body,* {    font-family: MyFont; font-size: ${fontSize}px;text-align: left; line-height: ${lineHeight}px; letter-spacing: ${letterSpacing}px; color: ${color};    background-color: ${backgroundColor};}img{height: auto;max-width: 100%;}iframe {height: auto;max-width: 100%;}div{height: auto;max-width: 100%;}</style>`;  return css;};const markdownLinksMap = (text: string) => {  const markdownLinkReg = /\[([^\[\]]+)\]\(([^)]+)\)/img;  text = text.replace(markdownLinkReg, (substring, ...args) => {    const title = args[0];    const url = args[1];    const linkKey = `<a href="${url}">${title}</a>`;    return linkKey;  });  return text;};const codeInject = (args: { html: string, textStyle?: StyleProp<TextStyle>, style?: StyleProp<ViewStyle> }): string => {  const textWithoutMarkdown = markdownLinksMap(args.html);  return (`<html><head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">    ${textStyleToCss(args.textStyle, args.style)}</head><body>${'<div style="color: '+ args.textStyle!.color +'">'+ textWithoutMarkdown +'</div>'}${style}</body>   `)};interface TextStyleProp extends TextStyle {  fontSize: number;  fontFamily: string;  lineHeight: number;  letterSpacing: number;  color: string;  fontUrl: string;}interface Props {  html: string;  navigateToWebview?: (url: string) => void;  style?: StyleProp<ViewStyle>;  textStyle?: StyleProp<TextStyleProp>;}interface State {  correctHtml: string;  height: number;}export class AutoHeightWebView extends React.Component<Props, State> {  public static getDerivedStateFromProps(props: Props, state: State) {    if (props.html) {      const correctHtml = codeInject(props);      return { correctHtml };    }    return null;  }  private webview: any;  constructor(props: Props) {    super(props);    this.state = {      correctHtml: codeInject(props),      height: 120,    };  }  public componentWillUnmount(): void {    if (this.webview) {      this.webview.stopLoading();      this.webview = null;    }  }  public render() {    if (!(this.props.html && this.props.html.length > 0)) {      return (<View />);    } else {      return (<View style={[SS.container, this.props.style]}><WebView            ref={this.setWebView}            automaticallyAdjustContentInsets={true}            source={{ html: this.state.correctHtml, baseUrl: '' }}            onMessage={this.onMessage}            javaScriptEnabled={true}            injectedJavaScript={`${postMessage};document.body.scrollHeight;`}            style={{ height: this.state.height }}            onNavigationStateChange={this.onNavigationChange}            domStorageEnabled={true}            scalesPageToFit={Platform.select({ios: undefined, android: true})}            startInLoadingState={true}            scrollEnabled={true}            showsHorizontalScrollIndicator={false}            showsVerticalScrollIndicator={false}            bounces={false}            originWhitelist={['*']}          /></View>      );    }  }  private onNavigationChange = (event: NavState): void => {    if (event.title) {      const htmlHeight = Number(event.title); //convert to number      if (htmlHeight && this.state.height !== htmlHeight) {        this.setState({ height: htmlHeight });      }    }  }  private onMessage = (event: NativeSyntheticEvent<WebViewMessageEventData>): void => {    const url = event.nativeEvent.data;    if (this.props.navigateToWebview) {      this.props.navigateToWebview(url);    } else {      Linking.openURL(url);    }  }  private setWebView = (webview: any): void => {    this.webview = webview;  };}const SS = EStyleSheet.create({  container: { flex: 1, overflow: 'hidden' },});

How can I initialize a class instance in a stateless function component in React?

$
0
0

Using a stateful pattern, I usually initialize a kind of helper class in my constructor and consume its methods in some component lifecycle methods like below:

class StatefulComponent extends Component {  constructor(props) {    super(props);    this.helper = new HelperClass();  }  componentDidMount() {    this.helper.doSomething();  }}

Now, I wanted to convert the same logic into a stateless function component like this:

const StatelessFunction = (props) => {   this.helper = new HelperClass();   useEffect(() => {     this.helper.doSomething();   }, []);}

But I worried when I saw that this component is being called every prop change from the beginning.And this made me think that my class instance is being created over and over. Am I wrong? Is there anything I can do for preventing re-creation of my class and use a ref instead?

I came across useRef but not sure if it fits my case.

How to remove Promise from a function? [duplicate]

$
0
0

My goal is to get the data from a method. The method return a Promise<BluetoothDevice[]>.

I would like to create a 2nd method to invoke the 1st method. The 2nd method should not return a Promise, instead it should return the data immediately.

This is the interface

interface BluetoothModule {  getBondedDevices(): Promise<BluetoothDevice[]>;}

This is how I plan to use it.

const App = () => {  const bluetoothList = BluetoothModule.getBondedDevices();  console.log(bluetoothList);  return <Text>Hello, this is what the user see.</Text>}

What I've tried

  1. Create a global method.
const getBondedDevices = async () => await BluetoothModule.getBondedDevices(); // This returns Promise<BluetoothDevice[]>
  1. Create a global method
const getBondedDevices = BluetoothModule.getBondedDevices();const App = () => {  const bluetoothList = getBondedDevices; // this returns the list, somehow... I find it weird. I will post the log below.  const bluetoothList2 = BluetoothModule.getBondedDevices(); // this does not return the list.  console.log(bluetoothList);  console.log(bluetoothList2);  return <Text>This is what the user see</TexT>}

This is the log for the 2nd method

{"_U": 0, "_V": 1, "_W": [{"address": "00:13:04:84:03:07", "isConnected": false, "name": "BTHP1"}, {"address": "00:13:04:84:03:6F", "isConnected": false, "name": "BTHP1"}], "_X": null}{"_U": 0, "_V": 0, "_W": null, "_X": null}

Async does wait for data to be returned in a redux-thunk function

$
0
0

I've being trying populate my redux store with data that comes from my mongo-db realm database.Whenever I run the function below it will execute fine but the problem is data will be delayed and ends up not reaching my redux store.

My thunk function:

export const addItemsTest = createAsyncThunk("addItems",  async (config: any) => {    try {      return await Realm.open(config).then(async (projectRealm) => {        let syncItems = await projectRealm.objects("Item");        await syncItems.addListener((x, changes) => {          x.map(async (b) => {            console.log(b);            return b;          });        });      });    } catch (error) {      console.log(error);      throw error;    }  });

and my redux reducer:

  extraReducers: (builder) => {      builder.addCase(addItemsTest.fulfilled, (state, { payload }: any) => {        try {          console.log("from add Items");          console.log(payload);          state.push(payload);        } catch (error) {            console.log(error)         }      });  }

Expected Results:My redux store should have these data once addItemsTest return something:

[{itemCode: 1,itemDescription: 'Soccer Ball',itemPrice: '35',partition: 'partitionValue',},{itemCode: 2,itemDescription: 'Base Ball',itemPrice: '60',partition: 'partitionValue',}]

Actual Results:Console Results

Viewing all 6288 articles
Browse latest View live


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