Home > Mobile >  I can't change value of a TextInput
I can't change value of a TextInput

Time:04-06

This is de code:

import { View, TextInput } from 'react-native';
import { styles } from './styles';
import { useState } from 'react';
import { getData } from '../../controllers/storages';

export default function Profile() {
    const [name, setName] = useState('');

    getData('user').then((res)=>{
        let a = JSON.parse(res)
        setName(a.name)
        })


  return (
    <View  style={styles.contender}>
        <View>
            <TextInput style={styles.email}        
                onChangeText={newText => setName(newText)}
                defaultValue={name}   
                placeholder="Enter username"           
            />
        </View>
    </View>
  );
}

I'm bringing the value name from a server and it gets print in the input, that works fine but when I try to modify that value it gets back to the original value very quickly. I've been reading threads and the most similar that I found was this:

TextInput with value doesn't change value

They put this link https://reactnative.dev/docs/handling-text-input which is very interesting but it doesn't work in my case, I believe it's because they are working with an empty string from the begining. The other answers I can't follow, I get lost when they mention this.state and the object info.

Also I tried changing the property value to defaultValue as you can see, but still it doesn't work.

I just want to print the value in the input that comes from the server and also be able to change it and put it in the same useState variable (name)

CodePudding user response:

Each time you change the state of the name your component is re-rendered so your function getData is called.

If you want to call your server only when your component is mounted for the first time you should use a useEffect.

import { View, TextInput } from 'react-native';
import { styles } from './styles';
import { useState,useEffect } from 'react';
import { getData } from '../../controllers/storages';

export default function Profile() {
    const [name, setName] = useState('');

    useEffect(getData('user').then((res)=>{
        let a = JSON.parse(res)
        setName(a.name)
        }),[]);
    


  return (
    <View  style={styles.contender}>
        <View>
            <TextInput style={styles.email}        
                onChangeText={newText => setName(newText)}
                defaultValue={name}   
                placeholder="Enter username"           
            />
        </View>
    </View>
  );
}
  • Related