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

Thumbnail hides after position:relative

$
0
0

I have a screen where I am using a Thumbnail and a UserInfoContainer, which is a PanGestureHandler(React native animation element that scrolls up). I want that even when I scroll up my UserInfoContainer container, the Thumbnail should stay on top of it at the same position.

export const Screen: React.FunctionComponent = () => {  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.iconsContainer}><TouchableOpacity          style={styles.cross}><Thumbnail            source={{              uri:'https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-512.png',            }}          /></TouchableOpacity><HamburgerIcon style={styles.hamburgerIcon}/></View><View style={styles.infoContainer}><UserInfoContainer /></View></View></SafeAreaView>  );};export const styles = StyleSheet.create({  safeAreaViewContainer: {    flex: 1,  },  container: {    backgroundColor: '#323443',    flex: 1,  },  iconsContainer:{    flexDirection: 'row'  },  cross: {    paddingTop: moderateScale(30),    paddingLeft: moderateScale(20),    zIndex: 100,  },  infoContainer: {    flex: 1,  },});

I have added a zIndex but now when I add position: 'absolute', my thumbnail just disappears. This has worked with another FontAwesomeIcon but its not working here in case of my Thumbnail. How can I fix this?


Border Extends out of outline

$
0
0

I have a simple textbox to which i have given an outline. However, If you look closely you will see that the border and the border outline dont match. The white color of the View extends out of the border outline as well. How can I fix this?

export const AddressTextBox: React.FunctionComponent<AddressTextBoxProps> = ({  placeName,}) => {  return (<View style={styles.textBox}><Text style={styles.text}>{placeName}</Text></View>  );};export const styles = StyleSheet.create({  textBox: {    backgroundColor: 'white',    height: moderateScale(50),    width: '70%',    marginTop: moderateScale(40),    alignSelf: 'center',    borderRadius: moderateScale(20),    borderColor: '#383838',    borderWidth: 0.3,    alignItems: 'center',    flexDirection: 'row',  },  text: {    fontSize: moderateScale(13),    flex: 1,    marginHorizontal: 10,    textAlign: 'center',  },});

enter image description here

Edit:

The problem doesn't exist in iOS simulator but does occur in Android phones.

Successfully uploaded image to Cloudinary from React Native does not return URL

$
0
0

I'm trying to upload image from React Native app to Cloudinary.The image appears on Dashboard, but I don't get secure_url.

Here is my code:

  async uploadImage(photo: ImagePickerResponse, id: string): Promise<string> {    return new Promise<string>(async (resolve, reject) => {      const uploadPreset = 'bbbbbb';      const cloudName = 'aaaaa';      const body = new FormData();      const uri: string =        Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', '');      const type = photo.type;      const name = `eMia${id}.jpeg`;      const file = {uri, type, name};      body.append('file', file);      body.append('upload_preset', uploadPreset);      body.append('cloud_name', cloudName);      const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;      fetch(url, {method: 'POST', body})        .then((res) => {          // I don't have Body here so i don't have the image url :(          console.log(res);          res.json();        })        .then((json) => {          console.log(json);          const url = json.secure_url;          console.log(url);          resolve(url);        })        .catch((err) => {          reject(err);        });    });  }

Response:

enter image description here

How to handle setInverval and clearInterval on react native

$
0
0

I want to change the value of state [time] every second when a button is pressed. I have the code below, but unfortunately the code doesn't work.Do you have any suggestion on how can I handle this issue ?

Many thanks !

import React,{useState} from 'react';import {View,Text,StyleSheet,TouchableOpacity} from 'react-native';import { AntDesign } from '@expo/vector-icons';const TimeButton = () =>{  const [time,setTime] = useState(10)  let intervalId:any = null;  return(<View style={styles.container}><TouchableOpacity><AntDesign name="caretleft" size={24} color="black" /></TouchableOpacity><Text>{time}</Text><TouchableOpacity onPressIn={() => {        intervalId = setInterval(setTime(time+1), 1000)        }} onPressOut={() => clearInterval(intervalId)}><AntDesign name="caretright" size={59} color="black" /></TouchableOpacity></View>  )}const styles = StyleSheet.create({  container:{    flex:1,    flexDirection:'row',    alignItems:'center',    justifyContent:"center"  }})export default TimeButton;

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

$
0
0

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

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

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

React Native version: 0.60.5

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

Typescript: Generic prop doesn't infer the type correctly

$
0
0

I have a following code:

interface Data {  [x: string]: number;}type Unpacked<T> = T extends (infer U)[]  ? U  : T extends (...args: any[]) => infer U    ? U    : T extends Promise<infer U>      ? U      : T;interface Props<T extends Data[]> {  data: T  xLabel: Extract<keyof Unpacked<T>, string>;  yLabel: Extract<keyof Unpacked<T>, string>;}const Chart = <T extends Data[]>({ data, xLabel, yLabel }: Props<T>): ReactElement => {  const styles = useStyles();  return (<View style={styles.container}><VictoryChart width={350} theme={VictoryTheme.material}><VictoryArea data={data} x={xLabel} y={yLabel} /><VictoryAxis /></VictoryChart></View>  );};const data = [  { quarter: 1, earnings: 13000 },  { quarter: 2, earnings: 16500 },  { quarter: 3, earnings: 14250 },  { quarter: 4, earnings: 19000 },];const Home = (): ReactElement => {  const styles = useStyles();  return (<ScrollView      showsVerticalScrollIndicator><Block><Chart data={data} xLabel="abc" yLabel="earnings" /></Block></ScrollView>  );};

Based on my understandings, xLabel="abc" should result in error because it is not the key of the data ("quarter" or "earnings" only in this case). However, unfortunately, xLabel and yLabel is type of "string", which's not what I expected. Did I do anything wrong?

React: Iterating through Array of Objects

$
0
0

This is the way FileObject is built and I need help in figuring out how to iterate and find a value based on the date provided.

    interface MyProps{      date: string;      cDataFileName?: string | undefined;      iDataFileName?: string | undefined;    }

And in dev tools it shows up like this..

 FileObject: Array(4)0: {date: "8/26/2020", cDataFileName: : "small_range_c-compressed.json", influenzaDataFileName: "mall_range_f-compressed.jso"}1: {date: "8-24-2020", cDataFileName: : "small_range_c-compressed.json", iDataFileName: : "mall_range_f-compressed.jso"}2: {date: "8-13-2020", cDataFileName: : "small_range_c-compressed.json", iDataFileName: : "mall_range_f-compressed.jso"}3: {date: "7-15-2020", cDataFileName: : "small_range_c-compressed.json", iDataFileName: : "mall_range_f-compressed.jso"}length: 4

What I need to be able to do is find if in FileObject data exists for a date of say "8/26/2020"

and get the cDataFileName and IDataFileName values for it.

const today = "8/26/2020";  console.log("testing" + FileObject [today as any]);  // Its coming as testingUndefined.  if (today in FileObject ) {    console.log("today" + today);  // Not even going there  }

Please help me figure out a best way to iterate through this array of objects to get based on the date "8/26/2020" provided.

-----------Update 1----------This is how I had values aded to FileObject.

const FileObject: MyProps[] = [];     FileObject.push({                date: file,                cDataFileName: MycovidFileName,                iDataFileName: MyinDataFileName,              });

Property missing type in React/Typescript while trying to pass a bool and interface to component state?

$
0
0

I am new to React and Typescript and I can't find the correct way I should be passing these into the React.Componet state. My code still works as expected but I would like to know what I am doing wrong!

class App extends React.Component<{}, { isLoading: boolean, thisCoffeeShop: ICoffeeShop }> {constructor(props: Readonly<{}>) {    super(props);    this.state = {        isLoading: true                        }       }//....}

}

I assume its Typescript throwing me

"Property 'thisCoffeeShop' is missing in type '{ isLoading: true; }' but required in type 'Readonly<{ isLoading: boolean; thisCoffeeShop: ICoffeeShop; }>'."

Component fails to auto import types from index.d.ts file in react native

$
0
0

I have a component called ColorBox, and inside of its folder i have the component itself, style of it and an index file and the index.d.ts file for my types:

  ColorBox   |- Colorbox.tsx   |- index.ts   |- styles.ts   |- index.d.ts

Here is my index.d.ts file:

export interface IProps {  colorName: string;  colorHex: string;}export interface IBGColor {  backgroundColor: string;}

and this is my ColorBox.tsx component:

import React from 'react';import { View, Text, StyleSheet } from 'react-native';import styles from './styles';const ColorBox: React.FC<IProps> = ({ colorName, colorHex }) => {  const boxColor: IBGColor = {    backgroundColor: colorHex,  };  return (<View style={[styles.box, boxColor]}><Text style={styles.boxText}>{colorName}</Text></View>  );};export default ColorBox;

the problem is that the IProps and IBGColor types does not auto imported from index.d.ts file, how does it works, i been read a lot of articles about typescript and ther were mentioned that if you put an index.d.ts file inside of of the module, typescript will rely on that and try to find types from that file, but why it does not work in my component? any hint of help will be appreciated.

i mean should i explicitly import used types inside of my module? if so, then what is the benefit that index.d.ts file provides to us?

also i use regular react-native init project, not any other fancy boilerplates!

How to Write Unit Test Case for Geo-Location on Use Effect react [closed]

$
0
0

Hi am new to jest test cases on reactcan someone Guide me approach to write Unit Test Case for geolocation on React UseEffet method and Thanks in Advance !

    useEffect(() => {        const getMyLocation = () => {          const location = window.navigator && window.navigator.geolocation;          if (location) {            location.getCurrentPosition((position) => {              setIsAcceptedGeoLocation(true);              setCurrentLatLng({                latitude: position.coords.latitude,                longitude: position.coords.longitude,              });            }, (error) => {              setIsAcceptedGeoLocation(false);              console.error('error', error);            });          }        };        getMyLocation();      }, []);

How to create new exceptions that extends an initial Error with TypeScript 2.9?

$
0
0

I wrote a small function to cascade errors in React & React Native with TypeScript:

/** * Function that takes an error and trow an enriched error * @param error the original error * @param func the name of the function trowing the error * @param params the parameters passer to the function * @param custom a custom message to add* * @returns an enriched error */const throwR = (error: Error, func?: string, params?: any, custom?: string) => {  // Parse params in an human readable form  let parsedParams: string = ''  if (params && typeof params === 'object') {    try {      parsedParams = JSON.stringify(params)    } catch (err) {      parsedParams = `${params.toString()} (JSON.stringify returned: ${err})`    }  } else {    try {      parsedParams = params.toString()    } catch (err) {      parsedParams = `<params.toString(): ${err}>`    }  }  // Handle the case where no error message is provided  if (!error) {    try {      console.log(`on ${func}(${parsedParams})${''+ custom}: No error message provided to throwR`)    } catch (err) {      console.log(`No error message provided to throwR and unable to build this message: ${err}`)    }  }  // build the error message  let message: string = ''  try {    message = `on ${func}(${parsedParams})${''+ custom}: ${error}`  } catch (err) {    message = `${error} (could not build enriched message: ${err})`  }  // build the new error  const newError = new Error(message)  // add the original error name  try {    newError.name = error.name  } catch (err) {    console.log(`on throwR, could not add a name to the error: ${error}`)  }  // by the end, throw the error  throw newError}export default throwR

Then I use it with:

const myFunction(params) => {  try {    // potentially faulty code  } catch (error) {    throwR(error, 'myFunction', params, 'custom message')  }}

I went on forums and saw that most people were using a custom error class then:

const myFunction(params) => {  try {    // potentially faulty code  } catch (error) {    throw new CustomError(error, customParameter)  }}

I'm a begineer and don't yet understand well the implication of each method. I would like to avoid a big pitfall that would later mean that I need to refactor all my code.

Could you explain me the implications of each approach and point me to a correct method for custom errors and cascading errors?

Thanks

formik error shows up after dismissing keyboard

$
0
0

I have a formik form where I take an input and run a graphql query on submitting the form. If the query returns some data, I render a list to show the items returned. However, when I see the list, the keyboard is not hidden automatically.

Hence, I added Keyboard.dismiss() to the onCompleted of my query. However, this causes the formik error to show up immediately after the form is submitted and data is returned/rendered. For instance, the error suggests that the input field should not be empty. The error should only show up when the form is re-submitted without an input. Right now, only the list should be rendered. Why is the keyboard interfering in this?

export const AddFriendScreen: React.FunctionComponent = () => {  const initialValues: FormValues = {    input: '',  };  const [showFlatList, setShowFlatList] = useState<UsersLazyQueryHookResult>('',  );  const [loadUsers, { data }] = useUsersLazyQuery({    onCompleted: () => {      setShowFlatList(data);      Keyboard.dismiss();    },  });  const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => {    loadUsers({      variables: {        where: {          OR: [            { phoneNumber: newPhoneNumber },],        },      },    });    helpers.resetForm(); };  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.searchTopContainer}><View style={styles.formContainer}><Formik            initialValues={initialValues}            onSubmit={handleSubmitForm}            validationSchema={validationSchema}>            {({ handleChange, handleBlur, handleSubmit, values }) => (<View style={styles.searchFieldContainer}><View style={styles.form}><FieldInput                    handleChange={handleChange}                    handleBlur={handleBlur}                    value={values.input}                    fieldType="input"                    icon="user"                    placeholderText="E-Mail oder Telefonnummer oder Name"                  /><ErrorMessage                    name="input"                    render={(msg) => <ErrorText errorMessage={msg} />}                  /></View><View style={styles.buttonContainer}><ActionButton buttonText="Suchen" onPress={handleSubmit} /></View></View>            )}</Formik></View><View style={styles.listHolder}>          {data && showFlatList !== null && (<UsersFoundList              data={data}/>          )}</View></View></SafeAreaView>  );};

How to ensure that a partial have a given field with TypeScript?

$
0
0

I have a type "Post" as follow:

interface Post {  id?: string  title: string  content: string  tags?: string[]}

I need to use it in a React Native flatlist, where the id is needed. In this case the id is fetched.

<FlatList  data={posts as Array<Partial<Post>>}  renderItem={({ item }: { item: Partial<Post> }) => <ContentListItem post={item} />}  keyExtractor={(item: Partial<Post>) => item.id}  ListHeaderComponent={ListHeaderComponent}/>

There keyExtractor is underlined with:

Type '(item: Partial<Post>) => string | undefined' is not assignable to type '(item: Partial<Post>, index: number) => string'.

I tried to change keyExtractor={(item: Partial) => item.id} to:

keyExtractor={(item: {id: string} & Partial<Post>) => item.id}

There data is underlined with:

Type 'Partial<Post>[]' is not assignable to type 'readonly ({ id: string; } & Partial<Post>)[]'.

Is there an elegant solution for this?

Thanks

Map of refs, current is always null

$
0
0

I'm creating a host of a bunch of pages, and those pages are created dynamically. Each page has a function that I'd like to call at a specific time, but when trying to access a ref for the page, the current is always null.

export default class QuizViewPager extends React.Component<QuizViewPagerProps, QuizViewPagerState> {    quizDeck: Deck | undefined;    quizRefMap: Map<number, React.RefObject<Quiz>>;    quizzes: JSX.Element[] = [];    viewPager: React.RefObject<ViewPager>;    constructor(props: QuizViewPagerProps) {        super(props);        this.quizRefMap = new Map<number, React.RefObject<Quiz>>();        this.viewPager = React.createRef<ViewPager>();        this.state = {            currentPage: 0,        }        for (let i = 0; i < this.quizDeck!.litems.length; i++) {            this.addQuiz(i);        }    }    setQuizPage = (page: number) => {        this.viewPager.current?.setPage(page);        this.setState({ currentPage: page })        this.quizRefMap.get(page)?.current?.focusInput();    }    addQuiz(page: number) {        const entry = this.quizDeck!.litems[page];        var ref: React.RefObject<Quiz> = React.createRef<Quiz>();        this.quizRefMap.set(page, ref);        this.quizzes.push(<Quiz                key={page}                litem={entry}                index={page}                ref={ref}                pagerFocusIndex={this.state.currentPage}                pagerLength={this.quizDeck?.litems.length!}                setQuizPage={this.setQuizPage}                navigation={this.props.navigation}                quizType={this.props.route.params.quizType}                quizManager={this.props.route.params.quizType === EQuizType.Lesson ? GlobalVars.lessonQuizManager : GlobalVars.reviewQuizManager}            />        )    }    render() {        return (<View style={{ flex: 1 }}><ViewPager                    style={styles.viewPager}                    initialPage={0}                    ref={this.viewPager}                    scrollEnabled={false}>                    {this.quizzes}</ViewPager></View >        );    }};

You can see in addQuiz() I am creating a ref, pushing it into my map, and passing that ref into the Quiz component. However, when attempting to access any of the refs in setQuizPage(), the Map is full of refs with null current properties.

Passing refs on React Native with TypeScript: (property) React.MutableRefObject.current: null Object is possibly 'null'.ts(2531)

$
0
0

I have several fields on a React Native form and I would like that the focus jump from one to the next one each time the user validate the field with the virtual keyboard.

I came up with something like that:

<NamedTextInput          name={'email'}          ref={emailRef}          ...          onSubmitEditing={() => passwordRef.current.focus()}        /><NamedTextInput          name={'password'}          ref={passwordRef}          ...        />

On current I get a TypeScript error:

(property) React.MutableRefObject<null>.current: nullObject is possibly 'null'.ts(2531)

I tried to add ! and ? marks but it ends into:

Property 'focus' does not exist on type 'never'.ts(2339)

Any idea to solve this ?

Thanks


interface does not satisfy the constraint 'Record'. Index signature is missing in type 'StackParamList'.ts(2344)

$
0
0

With TypeScript 3.9, React Native, React Navigation...

I got error:

interface StackParamListType 'StackParamList' does not satisfy the constraint 'Record<string, object | undefined>'.  Index signature is missing in type 'StackParamList'.ts(2344)

on:

const HomeStack = createStackNavigator<StackParamList>()

In:

const HomeStack = createStackNavigator<StackParamList>()export interface StackParamList {  Home: undefined  Post: { post: Post }  Category: { category: Category }  Login: undefined  ForgotPassword: undefined'My profile': undefined'My partner': undefined  Parameters: undefined  Likes: undefined  Onboarding: undefined}/** * Home "stack navigator" * @summary this is the navigator for everything located under "home" */export default function HomeStackScreen() {  return (<><StatusBar backgroundColor={colors.background} barStyle="dark-content" /><HomeStack.Navigator screenOptions={screenOptions}><HomeStack.Screen          name="Home"          component={HomeScreen}          options={{            headerTitle: (props) => <Logo {...props} />,          }}        /><HomeStack.Screen name="Login" component={LoginScreen} /><HomeStack.Screen name="Post" component={PostScreen} options={{ headerTransparent: true, title: '' }} /><HomeStack.Screen name="Category" component={CategoryScreen} options={({ route }) => ({ title: route.params.category.id })} /><HomeStack.Screen name="ForgotPassword" component={ForgotPasswordScreen} /><HomeStack.Screen name="My profile" component={UserProfileScreen} options={{ headerTransparent: true, title: '' }} /><HomeStack.Screen name="My partner" component={UserPartnerScreen} /><HomeStack.Screen name="Parameters" component={UserParamScreen} /><HomeStack.Screen name="Likes" component={UserLikesScreen} /><HomeStack.Screen name="Onboarding" component={Onboarding} options={{ headerShown: false }} /></HomeStack.Navigator></>  )}

I don't understand why the interface would not satisfy the type 'Record<string, object | undefined>'.

I don't understand what "Index signature is missing" mean.

Do you have an idea?

Thanks

Array of objects do not render using setState and map

$
0
0

I am using typescript in a react-native project, and would like to render an array of objects that come from a query using AWS-Amplify, using the map function.I use setState (here setTracks) to declare my state.While it logs well in the console, the map function does not render anything.

Here is the code:

 import {useEffect, useState} from 'react'; import {   ScrollView,   SafeAreaView,   StyleSheet,   Image,   TouchableWithoutFeedback,   ImageBackground,   Dimensions } from "react-native"; import EditScreenInfo from '../components/EditScreenInfo'; import { Text, View } from '../components/Themed'; import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config) import { API, graphqlOperation } from 'aws-amplify' import { listTracks } from '../src/graphql/queries' export default function TabTwoScreen() {   const [tracks, setTracks] = useState<Array>([])   //const [tracks, setTracks] = useState([])   useEffect(() => {     fetchTracks()}, [])   async function fetchTracks() {     try {       const trackData = await API.graphql(graphqlOperation(listTracks))       console.log('trackData:', trackData.data.listTracks.items)       setTracks([trackData])       console.log('trackdata is: ', tracks)     } catch (err) {       console.log('error fetching tracks...', err)     }   };     return (<SafeAreaView style={styles.container}>         {           tracks.map((track, index) => (<View key={index} style={styles.item}><Text style={styles.name}>{track.song}</Text><Text style={styles.description}>{track.artist}</Text><Text style={styles.city}>{track.songUrl}</Text></View>           ))         }</SafeAreaView>     )   }```

route.params issue, "Object is possibly 'undefined'"with React-navigation/native and Typescript

$
0
0

I am getting Typescript tell me "route.params.TextNode" in the DetailsScreen is possibly undefined, it works but am I doing something wrong?Sorry about the chunk of code, I just not sure where the issue could be!

Here are my type declarations.

export type RootTabParamList = {    Settings: undefined;    //Search: undefined;};export type SettingsStackParamList = {    Settings: undefined;    Details: { TestNote: string };};export type SettingsRouteProp = RouteProp<RootTabParamList, 'Settings'>;export type SettingsScreenNavigationProp = CompositeNavigationProp<                                StackNavigationProp<SettingsStackParamList, 'Details'>,                                 BottomTabNavigationProp<RootTabParamList, 'Settings'>>;export type SettingsProps = {    navigation: SettingsScreenNavigationProp;    route: SettingsRouteProp;  };

Here are the navigators.

const Tab = createBottomTabNavigator<RootTabParamList>();export default function App() {    const scheme = useColorScheme();    return (<AppearanceProvider><NavigationContainer theme={scheme === 'dark' ? MyDarkTheme : MyLightTheme}><Tab.Navigator initialRouteName="Search"                                                 tabBarOptions={{ activeTintColor: 'tomato',                                                 inactiveTintColor: '#650900',                                }}>                    {/* <Tab.Screen name="Search" component={SearchStackScreen} /> */}<Tab.Screen name="Settings" component={SettingsStackScreen} /></Tab.Navigator></NavigationContainer></AppearanceProvider>  );}const SettingsStack = createStackNavigator<SettingsStackParamList>();function SettingsStackScreen() {  return (<SettingsStack.Navigator><SettingsStack.Screen name="Settings" component={SettingsScreen} /><SettingsStack.Screen name="Details" component={DetailsScreen} /></SettingsStack.Navigator>  );}function DetailsScreen({ route, navigation }: SettingsProps) {    return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text style={{color: 'red'}}>{route.params.TextNode}</Text></View>    );  }function SettingsScreen({ route, navigation }: SettingsProps) {    return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text>Settings screen</Text><Button          title="Go to Details"          onPress={() => navigation.navigate('Details', { TestNote: "TestHey" })}        /></View>    );  }

formik error showing before submitting the form

$
0
0

In my formik form, I take an input & run a graphql query after submitting the form. If the query returns some data, I render a list accordingly.

When I see the list, the keyboard is not hidden automatically.

I added Keyboard.dismiss() to the onCompleted of my query. However, this causes the formik error to show up immediately after the form is submitted and data is returned/rendered. For instance, the error suggests that the input field should not be empty. The error should only show up when we are trying to resubmit the form without an input. Right now, only the list should be rendered. Why is the keyboard interfering in this?

export const AddFriendScreen: React.FunctionComponent = () => {  const initialValues: FormValues = {    input: '',  };  const [showFlatList, setShowFlatList] = useState<UsersLazyQueryHookResult>('',  );  const [loadUsers, { data }] = useUsersLazyQuery({    onCompleted: () => {      setShowFlatList(data);      Keyboard.dismiss();    },  });  const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => {    loadUsers({      variables: {        where: {          OR: [            { phoneNumber: newPhoneNumber },],        },      },    });    helpers.resetForm(); };  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.searchTopContainer}><View style={styles.formContainer}><Formik            initialValues={initialValues}            onSubmit={handleSubmitForm}            validationSchema={validationSchema}>            {({ handleChange, handleBlur, handleSubmit, values }) => (<View style={styles.searchFieldContainer}><View style={styles.form}><FieldInput                    handleChange={handleChange}                    handleBlur={handleBlur}                    value={values.input}                    fieldType="input"                    icon="user"                    placeholderText="E-Mail oder Telefonnummer oder Name"                  /><ErrorMessage                    name="input"                    render={(msg) => <ErrorText errorMessage={msg} />}                  /></View><View style={styles.buttonContainer}><ActionButton buttonText="Suchen" onPress={handleSubmit} /></View></View>            )}</Formik></View><View style={styles.listHolder}>          {data && showFlatList !== null && (<UsersFoundList              data={data}/>          )}</View></View></SafeAreaView>  );};

delete Formik Error Message after submitting form

$
0
0

Upon entering my screen, there's no error displayed on the input field.

In my form, I take an input and run a graphql mutation on it. Once it's done, I reset the form. However, after resetting, I start seeing a Formik Error because the field is .required() and currently it's empty.

This error should only be shown when I am trying to submit the form without an input. It shouldn't show after I have submitted it once successfully.

  const handleSubmitForm = (    values: FormValues,    helpers: FormikHelpers<FormValues>,  ) => {    editLocationName({      variables: {      favouritePlaceId: route.params.id,      input: {customisedName: values.locationName}      },    });    helpers.resetForm();    helpers.setErrors({});  };.....<Formik            initialValues={initialValues}            onSubmit={handleSubmitForm}            validationSchema={validationSchema}>            {({ handleChange, handleBlur, handleSubmit, values }) => (<View style={styles.searchFieldContainer}><View style={styles.form}><FieldInput                    handleChange={handleChange}                    handleBlur={handleBlur}                    value={values.locationName}                    fieldType="locationName"                    placeholderText="Neuer Name"                  /><ErrorMessage                    name="locationName"                    render={(msg) => <ErrorText errorMessage={msg} />}                  /></View><View style={styles.buttonContainer}><ActionButton buttonText="Save" onPress={handleSubmit} /></View></View>            )}</Formik>

Validation Schema:

const favouriteLocationNameValidationSchema = yup.object().shape({  locationName: yup  .string()  .label('locationName')  .required('Required Field')});

How can I reset the error message along with the form?

setErrors({}) did not work for me.

Viewing all 6214 articles
Browse latest View live


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