Home > database >  How to change value from TextInput in react native from json data
How to change value from TextInput in react native from json data

Time:03-12

I would like to change the state from my value propreties, but my variable is a JSON.

import React, { useEffect, useState, useForm } from 'react';

import {
  Button,
  View,
  Text,
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
  Input,
} from 'react-native';
import { TextInput, Alert, Card, Title } from 'react-native-paper';

export default function Cadastrar({ route, titleMessage, messageField }) {
  //pega o id dos parametros de rota, exportado no arquivo MESSAGECARD.JS na ação de clicar
  const { id } = route.params;

  const [DADOS, setData] = useState([]);

  const getCardsMessages = async () => {
    const response = await fetch(
      `https://back-end.herokuapp.com/${id}`
    );
    const jsonObj = await response.json();
    setData(jsonObj);
  };

  useEffect(() => {
    getCardsMessages();
  }, []);

  const [titleMessage2, onChangeText] = useState("TESTE EVENT");
  const [selectedId, setSelectedId] = useState(null);

  const [search, setSearch] = useState('');
  
  const updateSearch = (text) => {
    setSearch(text);
  };

  return (
    <View style={{ flex: 1, padding: 24 }}>
      <FlatList
        data={DADOS}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View>
           
              <TextInput
              value={"ID: " item.id}
              extraData={selectedId}
              onPress={() => setSelectedId()}>
              </TextInput>

            <TextInput
              placeholder="Titulo"

              value={item.titleMessage}
              onChangeText={(text) => updateSearch(text)}

              ></TextInput>
           

            <TextInput value={item.messageField}>
            </TextInput>


            <TextInput
              placeholder="Titulo"
              value={titleMessage2}
              onChangeText={onChangeText}>
              </TextInput>


            <Text style={{ margin: 10, padding: 10 }}>
              <Button title="Atualizar Post" />
            </Text>
          </View>
        )}
      />
    </View>
  );
}

I have trying this, but how can i get the value of these props which come from a json: value={item.titleMessage}

and update the:

const [search, setSearch] = useState('');

if goes this way it works:

value={search}

Anything will help, i starting my studies in react! Thanks a lot

CodePudding user response:

Instead of calling updateSearch call your setSearch directly.

<TextInput
  placeholder="Titulo"

  value={search}
  onChangeText={text => setSearch(text)}
/>

Well, at the start I didn't understood your question and I refactored your code to a map as we normally do in react thinking that it was what you want... Just to don't just delete it i'll keep it there to you, it wont be used to your question but you can refactor to your response of the search :) Also, its better to call your hooks in lower case. So change DADOS to dados.

export default function Cadastrar({ route, titleMessage, messageField }) {
    ...
    if (DADOS[0]?.id != undefined) {
        return (
            <View style={{ flex: 1, padding: 24 }}>
                {
                    DADOS.map(dado => {
                        return (

                            <View key={dado.id}>

                                <TextInput
                                    value={"ID: "   dado.id}
                                    extraData={selectedId}
                                    onPress={() => setSelectedId()}
                                />

                                <TextInput
                                    placeholder="Titulo"

                                    value={dado.titleMessage}
                                    onChangeText={(text) => updateSearch(text)}
                                />


                                <TextInput
                                    value={dado.messageField}
                                />

                                <Text style={{ margin: 10, padding: 10 }}>
                                    <Button title="Atualizar Post" />
                                </Text>
                            </View>

                        )
                    })
                }
            </View>
        );
    } else {
        return (
            <div>DADOS não tem nada</div>
        )
    }
}

What I do there is, first check if the hook has data, if not will return a div saying that don't have any data, there you can put whatever you want. Then, if found data, I return your View with a map of the data inside.

To do the map you open a {}, that way you can write javascript inside the html, then you put your data to map, and for each data you return the component that you specify in the return.

Since you're returning many components you need some unique value to distinguish one to another, you do this by passing a unique key value to the element that wraps everything, in your case, other view. And since the id is a unique value, you pass the id in the key.

The rest is just put the values that you need to show in the components, beign it as props or writting the value inside the element.

I removed the titleMessage2 element since I assumed that it will be the 2nd id of your array of jsons.

CodePudding user response:

well you can create a state variable to select one and other state variable to alternatives

const [search, setSearch] = useState(yourJson);
const [selected, setSelected] = useState('');

and now in your function updateSearch

const updateSearch =(newValue)=>{
   setSelected(newValue)
}

and in the ui side you need to modify this

<TextInput
   placeholder="title"
   value={selected}
   onChangeText={(text) => updateSearch(text)}
></TextInput>
  • Related