0

im new in react-native, im passing data by navigation to my edit_note screen, once i received i set it to my states, but it doesnt work, if i print them, it shows their values, but setting to my states doesnt work, heres the code:

heres the Notes class, in the navigation function im passing the datas, data and note_number to Edit_note

render() {
    return (
        <>
        <View style = {this.styles.View}>
           <FlatList data = {this.props.data} renderItem = {({item}) => (<TouchableOpacity onPress = {() => this.props.navigation.navigate("Edit_note", {data: this.props.data, note_number: item.note_number})}><Text style = {this.styles.Text}>{item.title}</Text></TouchableOpacity>)} keyExtractor = {(item) => item.note_number.toString()}></FlatList>
        </View>
        </>
    );
}

in Edit_note im receiving it like this:

    class Edit_note extends Component {

    constructor() {
        super();
        this.state = {
            array_notes: [],
            note_number: "",
        }
    }
    componentDidMount() {
        const {params} = this.props.navigation.state;
        let x = params.note_number;
        this.setState({note_number: x});
        console.log(this.state.note_number);
    }
    render() {
        return (
           <Text></Text>
        );
    }
}

if i print x, it will print the note_number, but setting it into note_number, and print it, it doesnt show anything, why?

plus
  • 327
  • 3
  • 12
  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – glinda93 Aug 09 '20 at 08:16

2 Answers2

0

You actually set it but your console.log() fires before the change.

After a state changes component rerenders so you can try printing it on screen like;

render() {
    return (
       <Text>{this.state.note_number}</Text>
    );
}
Cappydh
  • 26
  • 1
  • 6
0

setState is asynchronous that means that the state indeed changes but the console.log right after the setState is not showing the change.

You can learn more about it here.

D10S
  • 1,468
  • 2
  • 7
  • 13