Hi everyone,
here is code in React. I dont know how to re-render this array prototype map in React?
import React, { useState, useEffect } from 'react';
const Help = () => {
const initialObject = [
{
fileName: 'Horizon.txt',
fileSize: 450,
},
{
fileName: 'Something.png',
fileSize: 2720,
},
],
[listFiles, setListFiles] = useState(new Map()),
newVal = {
fileName: 'TEST',
fileSize: 0,
};
useEffect(() => {
initialObject.forEach((el) => {
setListFiles(
listFiles.set(el.fileName, {
size: el.fileSize,
})
);
});
}, []);
const addNew = () => {
let temp = listFiles.set('test', newVal);
setListFiles(temp);
// after is executed, new value test is in state, but not rendered
};
const addNew2 = () => {
listFiles.set('test', newVal);
// after execution, new value test is in state, but not rendered
console.log(listFiles);
};
const deleteItem = () => {
let temp = listFiles;
temp.delete('Something.png');
setListFiles(temp);
console.log(temp);
// listFiles.delete('Something.png');
};
// solution is with counter, observe count nr of map keys in useEffect
// but is there a better solution?
return (
<>
<button onClick={addNew2}>Add new item into map</button>{' '}
<button onClick={deleteItem}>Delete Item</button>
{Array.from(listFiles).map(([key, val]) => {
return (
<div key={key}>
{key} = {val.size}
</div>
);
})}
</>
);
};
export default Help;