Search code examples
javascriptreactjsreact-nativecomponentsrender

I don't know why rendering doesn't work in react


This code is TODO APP which can add, and delete Note. However, when I run this code, It works 'Add' function , but when I try to delete note, It doesn't delete the note immediately. And when I write any word on TextInput, then it deletes the note that I tried to delete.

export function Note(props){ 
    return (
    <View>
    <View>
        <Text>{props.val.date}</Text>
        <Text>{props.val.note}</Text> 
    </View>
    <TouchableOpacity onPress={props.deleteMethod}>
        <Text>D</Text>
    </TouchableOpacity>
    
    </View>
    );   
}

export function MyqtwriteScreen({ navigation, route }) {

const [noteArray, setNoteArray] = useState([]);
const [noteText, setNoteText] = useState('');


let notes = noteArray.map((val, key) => {
    console.log('start');
    return <Note key={key} keyval={key} val={val}
        deleteMethod={() => deleteNote(key)} />
});
const addNote = ()=>{
    if (noteText) {
        var d = new Date();
        noteArray.push({
            'date': d.getFullYear() +
                "/" + (d.getMonth() + 1) +
                "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes(),
            'note': noteText,
        });
        setNoteArray(noteArray);
        setNoteText('');
    }
};
const deleteNote = (key)=> {
    noteArray.splice(key, 1);
    setNoteArray(noteArray);
    // setNoteText('');
    
};
return (
    <View style={styles.container}>
        <View>
            {notes}
        </View>
        <TextInput
            onChangeText={(noteText) => setNoteText(noteText)}
            value={noteText}
            placeholder='>>>note'
            placeholderTextColor='gray'
        ></TextInput>
        <TouchableOpacity onPress={addNote}>
            <Text>+</Text>
        </TouchableOpacity>
    </View>
);  
}

I don't know why rendering doesn't work! I'm struggling this problem for over 2days... Please Help me.....


Solution

  • Splice updates the actual array, for a component to rerender the array should be replaced by a new instance.

    const deleteNote = (key)=> {
        const newArray=[...noteArray];
        newArray.splice(key, 1);
        setNoteArray(newArray);    
    };
    

    By this it will be pointed to a new array.

    The reason for it to update when you change the text is the text causes a re render as the state is updated. You can also consider using the filter function of the array.