0

I'm trying to set new values to a state, but I can't do this with the methods, the state stills the same.

here a declare my state

 this.state = {
    notes: [],
    selected: null
    };
}

using componentDidMount I can update the state

  componentDidMount() {
this.setState({
  notes: this.service.notes,
  selected: {
       title: "vazio",
       text: "vazio"
     }
    });
  }

but when I use this methods to update, the state stills the same

  onSelect(note) {
   this.setState({
   selected: note
    });
  }
RBT
  • 24,161
  • 21
  • 159
  • 240
  • You need to call the onSelect method from it's own context by using my for example a lambda, like onSelect="()=> onSelect()". Problem here is the contract where "this" is referring to. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – n9iels Mar 21 '20 at 22:07
  • Yes, it's binding to my note that i'm passing in other component, do u know how can I update the state with that note? – Gabriel Barbosa Mar 21 '20 at 22:25
  • https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function – Max Mar 21 '20 at 22:56
  • Are you getting any erors? – HMR Mar 21 '20 at 23:44

2 Answers2

0

Have you tried?

onSelect = note => {
  this.setState({
  selected: note
 });
}

This gives the onSelect property access to the component scope

CreativeJoe
  • 63
  • 1
  • 5
0

Try

onSelect = (note) => () => {
   this.setState({
      selected: note
   })
}

It builds a callback function, providing note as an argument

Use it as follows

onSelect={onSelect(note)}

On whatever handler you are using

andy mccullough
  • 9,070
  • 6
  • 32
  • 55