What is the process for defining a state using React Native and TypeScript?

Recently, I've embarked on my journey with React Native and decided to incorporate TypeScript into my development process. As I attempted to set my state, an error popped up that reads as follows:

An issue arose while trying to assign the argument '{ pickerData: PickerData; }' to a parameter of type 'IRegisterScreenState | ((prevState: Readonly<IRegisterScreenState>, props: Readonly<IRegisterScreenProps>) => IRegisterScreenState | Pick<...>) | Pick<...>'.
  The type '{ pickerData: PickerData; }' was found incompatible with type 'Pick<IRegisterScreenState, "pickerData">'.
    Upon comparison, it seems the property 'pickerData' poses some compatibility issues.
      Specifically, the type 'PickerData' lacks several required properties from type 'ReactNativePhoneInput<typeof TextInput>': isValidNumber, getNumberType, getValue, getFlag, along with other essential attributes.

To resolve this dilemma, I scoured for ways to set states using TypeScript and stumbled upon a resource at https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native#adding-a-component. In this guide, they introduced interfaces State and Props. This made me ponder if crafting my interface for the component is allowed, similar to what others have done with IState and IProps. Failing which, pinning down the root cause of the error might prove challenging. It appears that the error stems from the line

this.setState({pickerData: this.phoneInputRef.current.getPickerData()});

import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
import PickerData from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : PickerData;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() { 
    if (this.phoneInputRef.current) 
      this.setState({pickerData: this.phoneInputRef.current.getPickerData()}); 
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef.current);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef.current)
      this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});

Answer №1

It seems like the PickerData type may be incorrect. Do you know where that type is coming from? I saw a request for TypeScript support in the plugin issues.

Maybe consider changing pickerData to

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : any;
}

and check what the getPickerData function returns. This way, you can define a proper type for its return value.

I also noticed you used

this.phoneInputRef.current.getPickerData()

while the documentation suggests using

this.phone.getPickerData()

but I'm not sure if it makes a difference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There are no matching overloads in React for this call

Below is an error message in the code. It seems to be related to the usage of <IHistorical[]> in useQuery, but unfortunately, I haven't found a solution for it yet. Overload 1 of 2, '(props: Props | Readonly<Props>): ReactApexChart& ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...

Strategies for extracting information from the database

I have a pre-existing database that I'm trying to retrieve data from. However, whenever I run a test query, it always returns an empty value: { "users": [] } What could be causing this issue? entity: import {Entity, PrimaryGeneratedColumn, Col ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Utilizing Typescript to extract type information from both keys and values of an object

I have a unique challenge of mapping two sets of string values from one constant object to another. The goal is to generate two distinct types: one for keys and one for values. const KeyToVal = { MyKey1: 'myValue1', MyKey2: 'myValue ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

How can we ensure in ReactJS that one API call has been completed before making another one?

How can we ensure one API call is completed before making the next call in reactJS? In my componentDidMount function, I need to check the length of data. When the length is more than 4, I first want to save the data and then retrieve it. componentDidM ...

What is the best way to assign a type based on a variadic type in TypeScript?

TypeScript playground link For my current project, I am designing a custom route handler creator for Express. The goal is to allow passing arbitrary assertions as initial arguments before invoking the route handler callback. Here's an example of how ...

Tips for toggling visibility in Angular 2

I utilized [hidden] in the following way where the value of "secondTab" is set to true. <form #siteForm="ngForm" novalidate (ngSubmit)="saveSite(siteForm.value,siteForm.valid)" class="admin-modal"> <div class="txt-danger">{{errorMessage}}&l ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Issue at 13th instance: TypeScript encountering a problem while retrieving data within an asynchronous component

CLICK HERE FOR ERROR IMAGE export const Filter = async (): Promise<JSX.Element> => { const { data: categories } = await api.get('/categories/') return ( <div className='w-full h-full relative'> <Containe ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Error in TypeScript: The object may be null when using the window.open method

Is there a way to implement this code in Typescript? window.open(externalUrl, '_blank').focus(); Encountering the following TypeScript error: Object is possibly 'null'.ts(2531) I attempted the following solution without success: ...

Differences between RxJs Observable<string> and Observable<string[]>

I'm struggling to grasp the concept of RxJS Observables, even though I have utilized the observable pattern in various scenarios in my life. Below is a snippet of code that showcases my confusion: const observable: Observable<Response> = cr ...

Instructions for adding a new property dynamically when updating the draft using immer

When looking at the code snippet below, we encounter an error on line 2 stating Property 'newProperty' does not exist on type 'WritableDraft<MyObject>'. TS7053 // data is of type MyObject which until now has only a property myNum ...