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

If else within a map

$
0
0

Each of the user relations object looks like this:

"userRelations": [    {"relatedUser": {"id": 4,"firstName": "Jack","lastName": "Miller"      },"type": "FRIEND"    },    {"relatedUser": {"id": 3,"firstName": "Rhena","lastName": "Tahoma"      },"type": "CONTACT"    }  ]

Currently, my code renders all relatedUsers. However, I only want to render those which have "type": "contact". Is it possible to check for this condition within the return

type RelatedUser = {    firstName: string,    lastName: string,    id: string,    phoneNumber: string,  };  type RelationType = {    type: string,  };export const ContactList: React.FunctionComponent<UserProps> = ({ data }) => {  if (!data) return null;  return (<View style={styles.users}>    {data.users.nodes[0].userRelations.map(      (item: { relatedUser: RelatedUser, type: RelationType}) => {        const userName = item.relatedUser.firstName.concat('').concat(item.relatedUser.lastName);        // if (item.type: "CONTACT"){        return (<View style={styles.item} key={item.relatedUser.id}><Text style={styles.userName}>{userName}</Text></View>        );      },    )}</View>  );};

React Native elements not rerendering after state change

$
0
0

I have been looking at this error for 2 days now, and I cannot seem to figure out how and why this is not working. I have a FlatList of ProductComponent elements in my app which can be bought and sold through the push on a TouchableHighlight component defined in the ProductComponent.
Below is the code of my FlatList component and the ProductComponent it renders:

The FlatList component:

    const ProductList: React.FC = () => {    const energyResources = useSelector((state: RootState) => state.energyResources).asImmutable();    const dispatch = useDispatch<RootDispatch>();    const coins = useSelector((state: RootState) => state.coins).coins;    const purchaseItem = (item: IEnergyResource): void => {        if (coins > item.price) {            dispatch.energyResources.increaseAmountOwned(dispatch.energyResources, item);            dispatch.coins.buy(dispatch.coins, item.price);            Alert.alert('Gekocht!','Je hebt zojuist de energiebron '+ item.name +' gekocht, '+'\nJe hebt nu nog €'+ coins +' Euro!'            );        } else {            Alert.alert('Niet gekocht','Sorry, je hebt niet genoeg geld om deze energiebron te kopen.'            );        }    };    const sellItem = (item: IEnergyResource): void => {        if (item.amountOwned > 0) {            dispatch.energyResources.decreaseAmountOwned(dispatch.energyResources, item);            dispatch.coins.sell(dispatch.coins, item.price);            Alert.alert('Verkocht!','De energiebron '+ item.name +' is verkocht, '+'je hebt nu €'+ coins +' Euro.'            );        }  else {            Alert.alert('Niet verkocht','Sorry, de energiebron '+ item.name +' kon niet worden verkocht, '+'je hebt er geen in je bezit.'            );        }    };    return (<FlatList            style={styles.list}            data={energyResources.toArray()}            renderItem={                ({ item }) => <ProductComponent                    resource={item}                    onPurchase={purchaseItem}                    onSell={sellItem}                    canSell={item.amountOwned > 0}                />            }            keyExtractor={(item) => item.name}        />    );}

Both the purchase and sell methods are defined in the FlatList-component, and then passed to the individual elements (I figured this was better than defining the functions in ProductComponent itself and having each rendered item call on the state).

The ProductComponent component:

export interface IProductProps {    resource: IEnergyResource;    onPurchase: Function;    onSell: Function;    canSell: boolean;}const styles = StyleSheet.create({    buttonRight: {        alignItems: 'center',        alignSelf: 'flex-end',        backgroundColor: Constants.Colors.DodgerBlue,        marginVertical: 5,        padding: 10,        width: 150    },    image: {        alignSelf: 'flex-start',        height: 100,        width: 100    },    listItem: {        borderBottomColor: Constants.Colors.Blue,        borderBottomWidth: 2,        flex: 1,        flexDirection: 'row',        marginLeft: 5,        marginBottom: 0,        paddingBottom: 5    },    productInfo: {        width: 300,    },    rightButtons: {        alignItems: 'center',        alignSelf: 'flex-end'    },    sell: {        backgroundColor: Constants.Colors.Red    },    textLeft: {        alignSelf: 'flex-start',        fontSize: 20,    }});const ProductComponent: React.FC<IProductProps> = (props) => {    return (<View style={styles.listItem}><Image source={props.resource.image.image} width={50} height={50} style={styles.image} /><View style={styles.productInfo}><Text style={styles.textLeft}>{props.resource.name}</Text><Text style={styles.textLeft}>€{props.resource.price}</Text><Text style={styles.textLeft}>Energiewaarde: {props.resource.energyValue} Watt</Text><Text style={styles.textLeft}>In bezit: {props.resource.amountOwned}</Text></View><View style={styles.rightButtons}><TouchableHighlight style={styles.buttonRight} onPress={() => props.onPurchase(props.resource)}>                    {/* eslint-disable-next-line react-native/no-inline-styles */}<Text style={{ color: Constants.Colors.White, fontWeight: 'bold', fontSize: 15 }}>Kopen</Text></TouchableHighlight><TouchableHighlight style={[styles.buttonRight, styles.sell]} disabled={props.canSell} onPress={() => props.onSell(props.resource)}>                    {/* eslint-disable-next-line react-native/no-inline-styles */}<Text style={{ color: Constants.Colors.White, fontWeight: 'bold', fontSize: 15 }}>Verkopen</Text></TouchableHighlight></View></View>    );};

The methods are present in the IProductProps interface and the calls seem to work (I am getting the defined Alert as though I have indeed purchased a product). However, after clicking OK in the alertbox, the counter for the specified product (defined in ProductComponent as props.resource.amountOwned) remains 0 and I am unable to sell that same product.

These are the methods defined in the state models which I am calling:

/** * Increases the amount of items the player owns. * * @param {List<IEnergyResource>} state - the current state of the app * @param {IEnergyResource} item - the item which was bought * @returns {List<IEnergyResource>} state */function increaseAmountOwned(state: EnergyResourcesState, item: IEnergyResource): EnergyResourcesState {    const itemIndex = state.indexOf(item);    const newItem = {        amountOwned: item.amountOwned++,        ...item    };    return state.set(itemIndex, newItem);}/** * Decreases the amount of items the player owns. * * @param {List<IEnergyResource>} state - The current state of the app * @param {IEnergyResource} item - the item which was sold * @returns {List<IEnergyResource>} state */function decreaseAmountOwned(state: EnergyResourcesState, item: IEnergyResource): EnergyResourcesState {    const itemIndex = state.indexOf(item);    const newItem = {        amountOwned: item.amountOwned--,        ...item    } as IEnergyResource;    return state.set(itemIndex, newItem);}const initialState: IEnergyResource[] =    [        {            name:'Windmolen',            price: 15,            energyValue:20,            environmentValue:-15,            image:{                maxSize:{                    width:0.2,                    height:0.2,                },                image: images.windmill,            },            amountOwned: 0,            amountTotal: 30,            amountPlaced: 0,            location:{                x:0.05,                y:0            },        },{            name:'Watermolen',            price: 15,            energyValue:15,            environmentValue:-10,            image:{                maxSize:{                    width:0.2,                    height:0.2,                },                image: images.turbine            },            amountOwned: 0,            amountTotal: 30,            amountPlaced: 0,            location:{                x:0.05,                y:0.3            },        },{            name:'Zonnepaneel',            price: 15,            energyValue:10,            environmentValue:-5,            image:{                maxSize:{                    width:0.2,                    height:0.2,                },                image: images.solarPanel            },            amountOwned: 0,            amountTotal: 30,            amountPlaced: 0,            location:{                x:0.3,                y:0            },        }    ]const resources = {    state: List(initialState),    reducers: {        place:(state: EnergyResourcesState, name: string): EnergyResourcesState =>            state = doMutateEnergyResource(state, name, true),        remove:(state: EnergyResourcesState, name: string): EnergyResourcesState =>            state = doMutateEnergyResource(state, name, false),        increaseAmountOwned: increaseAmountOwned,        decreaseAmountOwned: decreaseAmountOwned    },};

I am using Rematch Redux framework to work with the state.

It is probably a minor detail I am overlooking here, so any help or nudges in the right direction is greatly appreciated.

Thank you in advance!

VSCode react native no import errors detected in code

$
0
0

I have been using vscode for couple of years but recently with version 1.45 i don't see any errors detected while i code . For example , it does not validate whether the import statement is valid nor the modules inside is valid or not . Earlier it used to clearly mark it in red if a module is not found in the import statement but still declared .

Vscode treats unknown variables as "any" and does not show any error unless i run it in the simulator.

Secondly, whenever i type an object if an import statement is found i used to see the option highlighted and now i don't see that either.

Any clue on why this behavior in vscode?.

React Native Align button on top of keyboard for all devices

$
0
0

So I need to align a button Which is not at bottom om screen by design should be at middle of screen but it should align to be on top of the keyboard for all devices.

If you check this screenshot :

enter image description here

for Some devices I mange to do it, but in some others is not really aligned :

enter image description here

how can I manage this to work in all?

this is what I did so far :

<Padding paddingVertical={isKeyboardOpen ? Spacing.unit : Spacing.small}><Button      variant="solid"      label='Next'      style={styles.submitBtn}    /></Padding>

And isKeyboardOpen is just a method which will create a listner based on the platform return true if keyboard is open :

 Keyboard.addListener(  Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',  true  );

And submitBrn css class is :

submitBtn: {  margin: Spacing.base,},

expanding React ecosystem similar to Angular

$
0
0

Angular appears to come with everything which for the client-side. On the other hand, React comes by itself. Are there any common consensus on how to get expand React/React Native with typescript in order to get a similar experience as with Angular. Are there any books?

Return DB results from a function in a different file (React Native/Typescript + SQLite)

$
0
0

I'm trying to read data in one file from an SQLite database and return it to display in a different file.

Firstly, I'd like to be able to manipulate the data prior to displaying it, for example, return the results into an array I can loop through, run some calculations, then update the rows. Secondly, I'd like to display it in the component, but I can't even seem to do that.

I have a TSX file where I store my CRUD functions. Here's my read one that I want to call from a different file:

export const ReadSingleProject = (projectID: string) => {    SQLite.openDatabase({    name: "database.db",    createFromLocation: "~database.db",    location: "Library",  }).then((db) => {    db.transaction((tx) => {      tx.executeSql("SELECT * FROM projects WHERE projectID=?",        [projectID],        (tx, results) => {          var len = results.rows.length;          if (len > 0) {                      return results.rows.raw();          }        }      );    })      .catch((error: string) => {        console.log(error);      })      .then(() => {        db.close().catch((error: string) => {          console.log(error);        });      });  });};

And then in my component file, I'm simply trying to bring in the results:

useEffect(() => {     let project = ReadSingleProject(projectID);   }, []); 

But this 'project' object comes back saying undefined. I've tried splitting the results into a JSON object in File 1 and returning that to populate a JSON object File 2, but there doesn't appear to be any data, even though when I console log in File 1, the results are there correctly.

Could anyone help, please?

Thanks

Why can I use a variable before declaring it in JavaScript / TypeScript?

$
0
0

To my understanding, after ES6 and the introduction of let and const, a variable declared with them must be declared before it's used. However, I have run into many examples where my code runs just fine when I declare the variables after its use. For example, this is the code from (a simplified version of) the TypeScript template of React Native:

import React from 'react';import {StyleSheet, Text} from 'react-native';const App = () => {  return (<><Text style={styles.text}>Some text</Text></>  );};const styles = StyleSheet.create({  text: {    backgroundColor: 'blue',  },});export default App;

Here, styles are declared after they are used, and it even seems to be the idiomatic way to do it, but even ESLint highlights as no-use-before-define.

My question is: why does it still work?

.filter with a map in Typescript

$
0
0

I am using data that is returned via a graphql query. Each of the user relations object looks like this:

"userRelations": [    {"relatedUser": {"id": 4,"firstName": "Jack","lastName": "Miller"      },"type": "FRIEND"    },    {"relatedUser": {"id": 3,"firstName": "Rhena","lastName": "Tahoma"      },"type": "CONTACT"    }  ]

Currently, my code renders all relatedUsers regardless of what their typeis. However, I only want to render those which have "type": "contact". I am trying to use the . filterfunction but I am unable to do so.

type UserProps = {  data: UsersLazyQueryHookResult;};type RelatedUser = {    firstName: string,    lastName: string,    id: string,    phoneNumber: string,  };  type RelationType = {    type: string,  };export const ContactList: React.FunctionComponent<UserProps> = ({ data }) => {  if (!data) return null;  return (<View style={styles.users}>    {data.users.nodes[0].userRelations.map(      (item: { relatedUser: RelatedUser, type: RelationType}) => {        // if (item.type: "CONTACT"){        return (<View style={styles.item} key={item.relatedUser.id}>           ...</View></View>        );      },    )}</View>  );};

I tried using this: data.users.nodes[0].userRelations.filter(({ type }) => type === 'CONTACT').map(/*code*/)

but it gives me an error that:

Binding element 'type' implicitly has an 'any' type.ts(7031)

If I add : RelationType infront of type, I get 'RelationType' is declared but its value is never read.ts(6133) Binding element 'RelationType' implicitly has an 'any' type

What else can I do to filter out and map/render only CONTACT types.


React Native SectionList: What are the correct TypeScript types

$
0
0

I'm building a React Native app using TypeScript. I'm trying to use a SectionList. I followed the docs, and here is my code:

  renderSectionHeader = ({ section: { title } }: { section: { title: string } }) => (<ListItem title={title} />  );  render() {    const { sections } = this.props;    return (<SafeAreaView style={styles.container}><SectionList          keyExtractor={this.keyExtractor}          sections={[            {title: 'Title1', data: ['item1', 'item2']},            {title: 'Title2', data: ['item3', 'item4']},            {title: 'Title3', data: ['item5', 'item6']},          ]}          renderItem={this.renderItem}          renderSectionHeader={this.renderSectionHeader}        /></SafeAreaView>    );  }

But the line renderSectionHeader={this.renderSectionHeader} throws the following TSLint Error:

[ts]Type '({ section: { title } }: { section: { title: string; }; }) => Element' is not assignable to type '(info: { section: SectionListData<any>; }) => ReactElement<any> | null'.  Types of parameters '__0' and 'info' are incompatible.    Type '{ section: SectionListData<any>; }' is not assignable to type '{ section: { title: string; }; }'.      Types of property 'section' are incompatible.        Type 'SectionListData<any>' is not assignable to type '{ title: string; }'.          Property 'title' is missing in type 'SectionListData<any>'. [2322]

Are the types of SectionList broken? Or is the example wrong? Or am I doing something wrong?

forEach function in typescript

$
0
0

I am working with graphql returned data that looks like this:

"userRelations": [    {"relatedUser": {"id": 4,"firstName": "Jack","lastName": "Miller"      },"type": "FRIEND"    },    {"relatedUser": {"id": 3,"firstName": "Rhena","lastName": "Tahoma"      },"type": "CONTACT"    }  ]

I had to separate all those items which had the type: "FRIENDS". I did this and it worked perfectly:

    var friendArray = new Array();    for (let i in data.users.nodes[0].userRelations) {     if (data.users.nodes[0].userRelations[i].type == "FRIEND")    {        friendArray.push(data.users.nodes[0].userRelations[i]);    }  }

However, I read that using for loops and for in is not a good idea. Is there any other way to iterate and check all the objects without for loops? I tried using this but it doesn't give the correct results:

data.users.nodes[0].userRelations.forEach((object: Object)=> {    if (data.users.nodes[0].userRelations.type == "FRIEND")    {        friendArray.push(data.users.nodes[0].userRelations.object);    }})  

The friendsArray remains empty. What am I missing out?

Edit: After filtering the friends data, I want to render some items by mapping. I was trying to do something like this:

data.users.nodes[0].userRelations.map()
data.users.nodes[0].userRelations.filter(({ type }) => type === 'FRIEND').map(/*code*/)

but this gave me an error that:

Binding element 'type' implicitly has an 'any' type.ts(7031)

Error while adding NavigationContainer in react native with typescript

$
0
0

When I define my NavigationContainer on separate file I get following error:

'NavigationContainer' refers to a value, but is being used as a type here. Did you mean 'typeof NavigationContainer'?

But when I define it in App.tsx works.

import React from 'react'import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';const Stack = createStackNavigator();function AppNavigator() {  return (<NavigationContainer><Stack.Screen        name={Routes.SPLASH}        component={SplashScreen}        options={{          headerShown: false,        }}      /></NavigationContainer>  )}export default AppNavigator

What is my problem?

Include a JS file in a React-Native Typescript project

$
0
0

Basically I am trying to customize a library file written in plain javascript and put it as a local file in a React-Native typescript project, the moment I try to convert the .js file to .ts/.tsx file, it throws a lots of linting issues, so fixing it is bit chaotic so I thought of keeping it as .js file only but I don't want to make any changes in the tsconfig file(i.e., adding jsallow = true), I know their is a way of adding some .d.ts file but not sure will it work or not and if it is, then what would be the syntax.

Mocking with RN Detox

$
0
0

I am following the detox mocking guide with typescript. The app always prints console.log of X.ts file instead of X.e2e.ts file.

Dependency version.

react-native: 0.61.5,detox: 16.4.0

Metro Configuration:

"detox": {"test-runner": "jest","runner-config": "e2e/config.json","configurations": {"ios.sim.debug": {"binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/App.app","build": "RN_SRC_EXT=e2e.js,e2e.ts xcodebuild -workspace ios/App.xcworkspace -scheme 'App Test' -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build","type": "ios.simulator","device": {"type": "iPhone 11"        }      }    }  }

metro.config.js

const defaultSourceExts = require("metro-config/src/defaults/defaults").sourceExts;module.exports = {  transformer: {    getTransformOptions: async () => ({      transform: {        experimentalImportSupport: false,        inlineRequires: false      }    })  },  resolver: {    sourceExts: process.env.RN_SRC_EXT ? process.env.RN_SRC_EXT.split(",").concat(defaultSourceExts) : defaultSourceExts  }};console.log("default", defaultSourceExts);console.log("module.exports from e2e", module.exports);/** above console results into the followingdefault [ 'js', 'json', 'ts', 'tsx' ]module.exports from e2e { transformer:   { getTransformOptions: [AsyncFunction: getTransformOptions] },  resolver: { sourceExts: [ 'e2e.ts', 'js', 'json', 'ts', 'tsx' ] } }*/

/src/AppEvent.js

const logEvent = (): void => {  console.log("from non-test event file");};export default {  logEvent};

/src/AppEvent.e2e.ts

const logEvent = (): void => {  console.log("from test event file");};export default {  logEvent};

When I run detox build && detox test metro server doesn't log e2d files, So I had to run metro separately using RN_SRC_EXT=e2e.js,e2e.ts yarn start

React Native Typescript Formik typings of handleSubmit in onPress

$
0
0

I just started a project on React Native with Typescript and came along Formik in order to build form in my application.

I did the great formik tutorial guide and saw the use of formik with RN section in JS.

However, when I tried to translate this example into typescript, then I got the following typing error on the Button's onPress attribute:

No overload matches this call.  Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.      Types of parameters 'e' and 'ev' are incompatible.        Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.          Types of property 'nativeEvent' are incompatible.            Type 'NativeTouchEvent' is missing the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed, and 17 more.  Overload 2 of 2, '(props: ButtonProps, context?: any): Button', gave the following error.    Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.ts(2769)index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAt...

From what I understand, the handleSubmit function (e?: FormEvent<HTMLFormElement>) => void, accepts an event from a form submission (onSubmit attribute of a form element). Since there is no Form equivalent in RN, it complains receiving the (ev: NativeSyntheticEvent<NativeTouchEvent>) => void from the RN Button's onPress attribute.

In order to get rid of the error and keep going, I used this following workaround which I'm not satisfied with :

<Button              title="Do it !"              color={colors.red}              onPress={                (handleSubmit as unknown) as (                  ev: NativeSyntheticEvent<NativeTouchEvent>                ) => void              }/>

I'd like to know how should I solve this typing error properly.

CodeSandbox: App.tsx:32

Thank you for your help.

react Profiling not supported

$
0
0

Chrome React Dev Tool's Profile Tab Said to me "react Profiling not supported".\nBut, I'm Set at my webpack.config.prod.js.\n

Im followd all description in 'https://gist.github.com/bvaughn/25e6233aeb1b4f0cdb8d8366e54a3977'.What of I'm forget anything there site description?

My Chrome Dev Tool Said Image\n

-> my webpack config.

var buildConfig = merge(baseConfig, {  optimization: {    minimize: true  },  resolve: {    extensions: [".js", ".css"],    alias: {      styles: path.join(__dirname, ""),"react-dom$": "react-dom/profiling","scheduler/tracing": "scheduler/tracing-profiling"    }  },

This is My App.

import * as React from "react";import { Profiler } from "react";const logProfile = (  id: string,  phase: "mount" | "update",  actualDuration: number,  baseDuration: number,  startTime: number,  commitTime: number,  interactions: Set<any>) => {  console.log("Profiling ID", id);  console.log("Profiling phase", phase);  console.log("Profiling actualDuration", actualDuration);  console.log("Profiling baseDuration", baseDuration);  console.log("Profiling startTime", startTime);  console.log("Profiling commitTime", commitTime);  console.log("Profiling interactions", interactions);};class TeacherConfig extends React.Component {  render() {    return (<><Profiler id="application" onRender={logProfile}><div id="preload_hidden"><span>abcd</span><span style={{ fontWeight: "bold" }}>abcd</span><span className="set" /> <span className="unlimit" />{""}<span className="start" /><span className="time1" /><span className="time2" /> <span className="time3" /></div><Navigations /></Profiler></>    );  }}

This is part of my package.json .

"dependencies": {"react": "^16.9.0","react-dom": "^16.5.0","react-draggable": "^3.0.5","react-hot-loader": "^4.3.11","react-id-swiper": "^1.6.8","react-resize-detector": "^3.4.0","sass-loader": "^7.1.0","scheduler": "^0.10.0"}

Consume `index.d.ts` declaration file in source code

$
0
0

I would like to reuse the type definitions within index.d.ts when porting plain .js files to .ts in my project. However I get Cannot find name 'Type'.

I feel like this is some configuration issue I'm banging my head against.Any help, much appreciated - thanks.

The folder structure looks like this

<root>  - /javascript (all js files)  index.d.ts    (declarations)

This is my current tsconfig.json

{"compilerOptions": {    /* Basic Options */"target": "es2017",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */"module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */"lib": [ "es2017" ],                      /* Specify library files to be included in the compilation. */"allowJs": true,                          /* Allow javascript files to be compiled. */    // "checkJs": true,                       /* Report errors in .js files. */"jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */    // "sourceMap": true,                     /* Generates corresponding '.map' file. */    // "outFile": "./",                       /* Concatenate and emit output to single file. */    // "outDir": "./",                        /* Redirect output structure to the directory. */    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */    // "composite": true,                     /* Enable project compilation */    // "removeComments": true,                /* Do not emit comments to output. */"noEmit": true,                           /* Do not emit outputs. */    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */    /* Strict Type-Checking Options */"strict": true,                           /* Enable all strict type-checking options. */    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */    // "strictNullChecks": true,              /* Enable strict null checks. */    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */"skipLibCheck": true,                     /* Skip type checking of all declaration files (*.d.ts). */    /* Additional Checks */"forceConsistentCasingInFileNames": true,    // "noUnusedLocals": true,                /* Report errors on unused locals. */    // "noUnusedParameters": true,            /* Report errors on unused parameters. */    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */    /* Module Resolution Options */"moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */"baseUrl": "./javascript",                /* Base directory to resolve non-absolute module names. */    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */    // "typeRoots": [],                       /* List of folders to include type definitions from. */    // "types": [],                           /* Type declaration files to be included in compilation. */"allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */"esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */"resolveJsonModule": true,    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */    /* Source Map Options */    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */    /* Experimental Options */    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */  }}

Axios Post request in React Native

$
0
0

I am new to react native and trying to post a request to an api, but I am having different results and I am not able to understand why this is happening what I am missing.

Below is the code and after that a short description is given about the code.

import { Button, TextInput } from "react-native";import axios from "axios";const SignUp = (props: any) => {const { navigation } = props;const [data, setData] = React.useState({    name: "",    checkName: false,});const handleNameChange = (val: any) => {    if (val.length !== 0) {        setData({            name: val,            checkName: true,        });    } else {        setData({            name: val,            checkName: false,        });    }};const toSend = {    name: data.name,};async function handleSubmit() {    console.log("Component Did Mount");    let axiosConfig = {        headers: {"Content-Type": "application/x-www-form-urlencoded",        },    };    axios        .post("https://cloud-api.herokuapp.com/api/users/signup",            toSend,            axiosConfig        )        .then((response) => {            console.log(response);        })        .catch((error) => {            console.log(error);        });}<TextInput    placeholder="Name"    onChange={(val: any) => handleNameChange(val)}/>;return <Button title="signUp" onPress={handleSubmit}></Button>;};export default SignUp;

I am not able to demystify this error:

If I a add concrete value to the name state like this { name: "Carla" } and do not enter any value in the text field on front end and press the button, then my request is successfully posted without warning [1] and error[2].

But when I try to use front end to enter value in text box and then sent it on a button click then this warning [1] prompts on browser console and after some time the server respond back with [2].

[1]

index.js:1 Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the methodisDefaultPrevented on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See react-event-pooling for more information.

[2]

Access to XMLHttpRequest at'https://cloud-api.herokuapp.com/api/users/signup' from origin'http://localhost:19006' has been blocked by CORS policy: No'Access-Control-Allow-Origin' header is present on the requested resource. SignUp.tsx:121 Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:83) xhr.js:178 POST https://cloud-api.herokuapp.com/api/users/signup net::ERR_FAILED

Nested flatlist with array for JSON data - React Native

$
0
0

Trying to display them as list item, date(2020-05-10,2020-05-22 etc...) as header and Hokey, Shopping under the date headers as list item.

{"2020-05-10":[      {"title":"Hiking"      },      {"title":"Shopping"      }   ],"2020-05-22":[      {"title":"Hiking"      },      {"title":"Football"      }   ],"2020-05-28":[      {"title":"Hiking"      },      {"title":"Football"      },      {"title":"Cricket"      }   ]}

How to change position of rendered elements in react-based browser game?

$
0
0

So the project I am working on is a sort of online-roulette. It's a game that has up to 12 players and I need to position them around the table on approximately equal distance from each other no matter how many of them would play (so if I have two, five, seven, twelve or eleven players the distance between them should be the same at least from the first glance). I have a tableUserPlaces value which contains all the positioning values, but it is completely static. I need to set this variable in more dynamic way, but I can figure out how to get this done. Which properties change when the number of players changes and which of them can I tweak to get a new array of positions anytime I have new players' count? enter image description here

Here is the code for two relevant components

export interface IGamePlus extends Omit<IGame, "matches">  {  ticket: ITicket;  matches: IMatchPlus[];  requiredMatches: number;}class BestAtTableGame extends React.Component<IBestAtTable, IBestAtTableState> {  constructor(props) {    super(props);    this.state = {      createTicketIsOpen: false,      ticketIsOpen: false,      selectedTicket: {},      gameStatus: null,      showRuleIsOpen: false,      ruleData: null,      ruleClicked: false,      ruleType: 0 as number,    };  }  static getDerivedStateFromProps(props): any {    return {      gameStatus: {        gameCreated: props.game.status === gameDictionary.GAME_STATUS_CREATED,        gameStarted: props.game.status === gameDictionary.GAME_STATUS_STARTED      }    };  }  componentDidMount(): void {    window.resizeViewport();    const gameId = this.props.match.params.gameId;    this.props.gameTypeRequest({      getParams: {        id: gameId,        type: gameDictionary.GAME_TYPE_BEST_AT_TABLE      }    });    this.props.ticketsRequest({      getParams: {        gameId,        type: gameDictionary.GAME_TYPE_BEST_AT_TABLE      }    });  }  componentDidUpdate() {    if (this.props.rules && this.props.rules.length > 0 && !this.state.showRuleIsOpen) {      const currentGameRule = this.props.rules.find(item => {        return item.gameType === Number(this.state.ruleType);      });      if (currentGameRule && JSON.parse(currentGameRule.text).hasOwnProperty(localStorage.locale) && this.state.ruleClicked) {        this.setState({          showRuleIsOpen: true,          ruleData: JSON.parse(currentGameRule.text)[localStorage.locale]        });      }    }  }  componentWillUnmount(): void {    this.props.gameTypeReset({      type: gameDictionary.GAME_TYPE_BEST_AT_TABLE    });  }  switchModal = (e: any): void => {    this.setState({      ruleClicked: false    });    switchModalGlobal(this, e);  }  setTicket = (data: ITicket): void => {    this.setState({      selectedTicket: data,      ticketIsOpen: true    });  };  showRule = e => {    const type = e.currentTarget.dataset.rule;    if (!this.state.ruleData) {      this.props.getRulesRequest({        getParams: {          pageNumber: 1        }      });    }    this.setState({      ruleClicked: true,      ruleType: type,    });  };  renderPlaces = (): any => {    const { gameStatus } = this.state;    const { game, user, translate } = this.props;    const seatUnavailable =      game.tickets.find(({ player }) => player.id === user.id) || user.permissionLevel > userDictionary.USER_PLAYER_PERMISSION_LEVEL;    let placeCount = 0;    return tableUserPlaces.map((item, i) => {      if (seatsInTableAvailable[game.maxPlayers - 1 > 11 ? 11 : game.maxPlayers - 1].indexOf(item.place) !== -1) {        const ticket = game.tickets[placeCount];        placeCount += 1;        return (<UserPlace            key={i}            placeCount={placeCount}            seatUnavailable={seatUnavailable}            gameStatus={gameStatus}            ticket={ticket}            item={item}            game={game}            translate={translate}            setTicket={this.setTicket}            switchModal={this.switchModal}          />        );      }      return null;    });  };  render(): JSX.Element {    const { selectedTicket, createTicketIsOpen, ticketIsOpen, gameStatus, ruleData, ruleType, showRuleIsOpen } = this.state;    const { game, translate } = this.props;    return (<><CSSTransition in={showRuleIsOpen} unmountOnExit={true} timeout={200} classNames="modalWindowAnimation"><ShowRuleModal dataModal="showRuleIsOpen" ruleData={ruleData} ruleType={ruleType} switchModal={this.switchModal}/></CSSTransition><CSSTransition in={createTicketIsOpen} unmountOnExit={true} timeout={200} classNames="modalWindowAnimation"><CreateTicketModal            dataModal="createTicketIsOpen"            switchModal={this.switchModal}            game={game}            gameType={gameDictionary.GAME_TYPE_BEST_AT_TABLE}          /></CSSTransition><CSSTransition in={ticketIsOpen && game.status === gameDictionary.GAME_STATUS_STARTED}          unmountOnExit={true} timeout={200} classNames="modalWindowAnimation"><ViewTicketModal dataModal="ticketIsOpen" switchModal={this.switchModal} game={game} selectedTicket={selectedTicket} /></CSSTransition><div          className={cn("best-at-table-game", {"best-at-table-game__seats-disabled": !gameStatus.gameCreated          })}><div className="games__header"><div className="left-side"><img src="/assets/images/gameTiles/1.png" alt="" /><span>{translate("Best at Table")}</span><div className="info-link" data-rule={gameDictionary.GAME_TYPE_BEST_AT_TABLE} onClick={this.showRule}>?</div></div>            {game.id && (<div className="right-side"><img src="/assets/images/gameTiles/1.png" alt="" /><span>                  {game.tickets.length} / {game.maxPlayers}</span></div>            )}</div><div className="best-at-table__viewport-wrapper"><div id="viewport-wrapper"><div id="viewport"><div className="best-at-table-game__container">{game.id && this.renderPlaces()}</div></div></div><Link to="/best-at-table/games" className="btn gold-btn best-at-table-game__btn-back">{translate("Back")}</Link><Top game={game} translate={this.props.translate}/></div></div></>    );  }}export default withRouter(  connect(    (state: any) => ({      user: state.auth.user,      game: state.gamesTypes.bestAtTable.game,      rules: state.rules.rules,    }),    {      gameTypeRequest,      ticketsRequest,      gameTypeReset,      getRulesRequest,    }  )(withTranslate(BestAtTableGame)));

And this is like a database for positions

export const tableUserPlaces = [  {    place: 0,    _styles: { top: "0", left: "40%" },  },  {    place: 1,    _styles: {      top: "30px",      left: "66%",    },  },  {    place: 2,    _styles: {      top: "150px",      left: "79%",    },  },  {    place: 3,    _styles: {      top: "260px",      left: "84%",    },  },  {    place: 4,    _styles: {      top: "370px",      left: "79%",    },  },  {    place: 5,    _styles: {      top: "480px",      left: "66%",    },  },  {    place: 6,    _styles: {      top: "520px",      left: "42%",    },  },  {    place: 7,    _styles: {      top: "480px",      right: "66%",    },  },  {    place: 8,    _styles: {      top: "370px",      right: "79%",    },  },  {    place: 9,    _styles: {      top: "260px",      right: "84%",    },  },  {    place: 10,    _styles: {      top: "150px",      right: "79%",    },  },  {    place: 11,    _styles: {      top: "30px",      right: "66%",    },  },];export const seatsInTableAvailable = [  [0],  [0, 6],  [0, 3, 9],  [0, 3, 6, 9],  [0, 1, 3, 6, 9],  [0, 1, 3, 6, 9, 11],  [0, 1, 2, 3, 6, 9, 11],  [0, 1, 2, 3, 6, 9, 10, 11],  [0, 1, 2, 3, 4, 6, 9, 7, 8],  [0, 1, 2, 3, 4, 6, 9, 7, 8, 10],  [0, 1, 2, 3, 4, 5, 6, 9, 7, 8, 10],  [0, 1, 2, 3, 4, 5, 6, 9, 7, 8, 10, 11],];export const seatsAvailable = [  [0],  [0, 1],  [0, 1, 2],  [0, 1, 2, 3],  [0, 1, 2, 3, 4],  [0, 1, 2, 3, 4, 5],  [0, 1, 2, 3, 4, 5, 6],  [0, 1, 2, 3, 4, 5, 6, 7],  [0, 1, 2, 3, 4, 5, 6, 7, 8],  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],];

Polygon is not draggable

$
0
0

I drawn a polygon using MapboxGL.ShapeSource and added MapboxGLView.PointAnnotation on every point to make points draggable.

But i'm facing issues

When i finished the draw of Polygon, i'm not able to move or drag the polygon

 Polygon Data => {"coordinates": [[73.66673886505973, 21.78762724903116], [73.66889536107317, 21.791363112441147], [73.66555869310983, 21.79017760900554]]}

here my code

<MapboxGL.Animated.ShapeSource     id={'Polygon'}     maxZoomLevel={17}    onPress={(event: any) => {      console.log('Shape is pressed ', event);    }}    shape={{      type: 'Feature',      geometry: {        type: 'Polygon',        coordinates: coordinates,      },    }}><MapboxGL.FillLayer      id="routefill"      sourceID="Polygon"      style={{fillColor: fillColor}}    /><MapboxGL.LineLayer      id="routeline"      sourceID="Polygon"      belowLayerID="routefill"      style={{        lineWidth: 5,        // lineOpacity: 0.5,        lineJoin: 'round',        lineCap: 'round',        lineDasharray: [2, 2],        lineColor: strokeColor,      }}    /></MapboxGL.Animated.ShapeSource>

can anyone please help me how can i make polygon draggable

Viewing all 6218 articles
Browse latest View live


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