0

I'm learning React for a week and decided to make a blog for practice. I'm using React hooks and Redux Toolkit.

I want to upload files (images). There's a variable imageUrl:

const [imageUrl, setImageUrl] = useState("");

There's the input:

<input type="file" id="file" accept="image/jpeg, image/png" onChange={(e) => handleImageChange(e)}></input>

And there's a function handleImageChange:

const handleImageChange = e => {
        e.preventDefault();

        let reader = new FileReader();
        let file = e.target.files[0];

        reader.onloadend = () => setImageUrl(reader.result);

        if (file) reader.readAsDataURL(file);
    }

The problem is that setImageUrl doesn't update imageUrl immediately. It works only from the second try. But if I write this code in the event onChange of the input, all works fine.

Why does this happen and how can I fix it?

Shadowman
  • 245
  • 3
  • 11
  • With "if I write this code in the event onChange of the input" do you mean placing the function's code inline? – yuriy636 Mar 28 '20 at 18:16
  • @yuriy636 Yeah, that's what I mean – Shadowman Mar 28 '20 at 18:18
  • I'm unable to reproduce https://codesandbox.io/s/lucid-buck-5x61r – yuriy636 Mar 28 '20 at 18:21
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Shane Creedon Mar 28 '20 at 18:32
  • @yuriy636 Yeah, it renders fine, I know. But I need to get the url of picture, and to save it in Redux store. And if I write `console.log(imageUrl)` in the function after `reader.readAsDataURL()`, I get "empty string". – Shadowman Mar 28 '20 at 18:35
  • @ShaneCreedon No, it doesn't, because I'm using hooks, and they can't use callbacks. – Shadowman Mar 28 '20 at 18:38
  • @Shadowman Setting the state, whether in a class-based approach or with hooks is asynchronous. That's why you only see the change on the second time. I advise to use the useEffect hook as described here: https://stackoverflow.com/questions/55582013/react-hooks-state-variable-not-updating-after-rerender – Shane Creedon Mar 28 '20 at 18:47
  • @ShaneCreedon Got it, thanks for the advice! I've just created another function, and I add url to the store there. All works fine now. – Shadowman Mar 28 '20 at 18:53

0 Answers0