skip to Main Content

I simplified the problem I had in my application as follows. Even if I enter a new word in the TextInput, when I go back in the page it says "initial". Why doesn’t it write new value?

Actually, what I want to do here is to send the last entered text to redux as soon as I press the phone’s back button(hardwareBackPress). But it always sends the initial value. How can I solve this problem?

import { TextInput } from 'react-native'
import React, { useEffect, useState } from 'react'

export default function ChangeModel({ navigation }) {
    const [text, setText] = useState("initial")
  
    const onPressSave = () => {
        console.log(text)
    }

    useEffect(() => {
        return () => onPressSave()
    }, [])


    return (
        <TextInput
            value={text}
            onChangeText={setText}
            style={{ backgroundColor: "grey" }}
        />
    )
}

2

Answers


  1. you’re not set anything that makes the value change, try to set the state with new value:

    setText(newValue)
    

    if you handle with redux you should import the action first and dispatch it after that

    Login or Signup to reply.
  2. To get entered data you have to write a button component like this

    import { TextInput, Text, View, Button } from 'react-native';
    import React, { useState, useEffect } from 'react';
    
    export default function ChangeModel({ navigation }) {
    const [text, setText] = useState('initial');
    
    const onPressSave = () => {
     console.log(text);
    };
    
    useEffect(() => {
     return () => onPressSave();
    }, []);
    
    return (
     <View>
       <TextInput value={text} onChangeText={setText} />
       <Button title="Press me" onPress={onPressSave} />
     </View>
     );
     }
    

    When you click the button on the back of the phone, the state is default

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search