I want to save the input text to a state and use handleSave to create an item, but when I run handleSave, the console only outputs {name: "",description: "",} before it is updated.The console.log with useEffect outputs the updated state for each input, but I still cannot get the updated state with handleSave.I would appreciate it if you could tell me if you know how to improve it.
CreateItem.tsx
import React, { useState, useEffect } from "react";import { styles } from "style/style";import CloseIcon from "icons/Close";import InputText from "utils/InputText";const CreateItem = ({ navigation }: { navigation: any }) => { const [item, setItem] = useState({ name: "", description: "", }); const handleInputChange = (name: string, value: string) => { setItem({ ...item, [name]: value }); }; useEffect(() => { navigation.setOptions({ headerLeft: () => (<TouchableOpacity onPress={() => navigation.goBack()} style={{ padding: 12, margin: -12, }}><CloseIcon size={24} color="#000" /></TouchableOpacity> ), headerRight: () => (<Button title="save" onPress={handleSave} color="#000" /> ), }); }, [navigation]); useEffect(() => { console.log(item); }, [item]); const handleSave = () => { console.log(newItem); }; return (<View style={styles.container}><View style={styles.formGroup}><Text style={styles.formLabel}>Name</Text><InputText name="name" placeholder="Enter Name" value={item.name} onChangeText={(text) => handleInputChange("name", text)} /></View><View style={styles.formGroup}><Text style={styles.formLabel}>description</Text><TextInput style={styles.formInputMultiLine} placeholder="Enter description" multiline={true} value={item.description} onChangeText={(text) => handleInputChange("description", text)} /></View></View>
InputText.tsx
import React, { useState } from "react";import { View, Text, TextInput } from "react-native";import { styles } from "../style/style";interface InputTextProps { name: string; placeholder?: string; keyboardType?: "default" | "numeric" | "email-address" | "phone-pad"; value?: string; onChangeText?: (text: string) => void;}const InputText = ({ name = "name", placeholder = "Enter text", keyboardType = "default", value = "", onChangeText,}: InputTextProps) => { const [borderColor, setBorderColor] = useState("#EFEFEF"); const onFocus = () => { setBorderColor("#c09969"); }; const onBlur = () => { setBorderColor("#EFEFEF"); }; return (<View><TextInput style={[styles.formInput, { borderBottomColor: borderColor }]} placeholder={placeholder} keyboardType={keyboardType} value={value} onChangeText={onChangeText} onFocus={onFocus} onBlur={onBlur} /></View> );};export default InputText;