import React from "react";
import Button from "./Button";
import Section from "./Section";
import { Dragendrop } from "./Dragendrop";
export const RightBox = () => {
const [fileData, setFileData] = React.useState();
const [data, setData] = React.useState(null);
const [recieverAddress, setReceiverAddress] = React.useState("");
const handleFileData = (data) => {
setFileData(data);
};
const upload = () => {
if (fileData.length > 0) {
const reader = new FileReader();
reader.onload = function (fileEvent) {
const f = fileEvent.target.result;
setData(f);
console.log(data);
};
reader.readAsDataURL(fileData[0]);
}
};
//
const checkUser = () => {
};
return (
<div className="w-1/2 h-[45rem] mb-5 bg-stone-900 p-2 rounded-md">
<div className="flex gap-2">
<input
type="text"
onChange={(e) => {
setReceiverAddress(e.target.value);
}}
className="w-full p-3 font-code rounded-md"
placeholder="Reciever Id"
/>
<Button onClick={checkUser}>Check</Button>
</div>
<Section
className="w-full h-[580px] -mx-2 my-3"
crosses
customPaddings
id="data"
>
<div className="container">
<Dragendrop onFileData={handleFileData} />
</div>
</Section>
<div className="w-full">
<Button onClick={upload} className="w-full content-end flex">
Send
</Button>
</div>
</div>
);
};
On clicking send button, upload function runs,
according to upload function it should read file data and store to setData() state and
console.log(data),
but it don’t print files data on first click,
on second click it prints the data.
I got consfuse, why console.log(data) prints filedata on second click,not on first click.
so, the file data should print on the first click only.
2
Answers
by updating the state
data
with the settersetData(f)
, you are actually only telling React to update the state, but the state is not actually updated yet until the next render. Whenconsole.log(data)
runs the first time, the state does not yet hold the new value. By the second time you runconsole.log(data)
, that is, the second time you press the button, the state has been updated with the new value.React docs explaining why your situation happens.
The issue you’re experiencing is due to the asynchronous nature of the
setState
function in React. When you callsetData(f)
, it schedules an update to the component state but does not immediately change the value ofdata
. Therefore, when you callconsole.log(data)
right aftersetData(f)
, it logs the value ofdata
before the state update.To see the updated state immediately after setting it, you can use a callback or an effect hook. Here’s how you can modify your
upload
function to log the updated state using an effect hook:In this code, the
useEffect
hook will run every timedata
changes, logging the updated value. This way, you’ll see the updateddata
in the console immediately after you click the “Send” button.