I want to dynamically update my page’s content when an excel file is uploaded. I can handle the upload and convert it into a json array. The problem is that when I use setContent(json[x].Data) the Content stays empty.
I tried setting it just to the json array, but it did not work either.
This is my code:
const [Content, setContent] = useState([]);
const handleFileUpload = (e) => {
const reader = new FileReader();
reader.readAsBinaryString(e.target.files[0]);
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: "binary" });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const parsedData = XLSX.utils.sheet_to_json(sheet);
setContent(parsedData[10].Data);
console.log(Content);
};
};
The console.log shows, that the Content is just an empty object.
What am I doing wrong?
2
Answers
I think you don’t understand how React lifecycle (and useState) works.
When you set new value with setContent, Content will update AFTER component re-render.
So when you are trying to log Content into console, Content has its default value – which is an empty array.
Edit:
The useState updating looks like this:
set function -> rest of code reading -> re-render (component’s content has been updated -> useState variable update
If you want to get the updated value in console, you can either do
inside your function, as you have done already or do console logs outside your function as below:
Hope this helps.