-1

I'm currently using the React FilePicker tool which requires a "handFileChange" method. In that method, I'm trying to set my a file variable in my react state to the file that's used as a parameter for the method.

I'm trying to also implement a getter method that will return the current file. However, when I go to console.log the file from the getter method, I get a blank line

Any suggestions? Thanks

enter image description here

enter image description here

enter image description here

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
coder_coder123
  • 101
  • 2
  • 3
  • 9
  • 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) – Emile Bergeron Jan 26 '20 at 23:39

2 Answers2

1

setState() is not synchronous, use its callback instead

setState(
  { file: [file] },
  () => console.log(this.state.file)
);

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component...

https://reactjs.org/docs/react-component.html#setstate

Community
  • 1
  • 1
ButchMonkey
  • 1,873
  • 18
  • 30
0

With the official documentation of React : https://en.reactjs.org/docs/react-component.html#setstate

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

You must use function callback here :

setState(stateChange[, callback])

Example :

setState({file: [file]}, () => { console.log(this.state.file) });

Moreover, if you want to debug and watch the state and prop of component. I recommend you using React Developer Tool. It help so much easier https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi

SanjiMika
  • 2,664
  • 19
  • 19