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;

I figured myself, tough not sure if this method is optimal. Reading documentation one more time, react re-renders every time when we use setState. That being said, let focus myself only on this part. So, I will create new Map every time, like this (see code) and now react re-renders the component.

  const addNew = () => {
    var temp = new Map(listFiles); // mimic array shallow copy
    temp.set('test', newVal); // modify now the map
    setListFiles(temp); // setState for react to change
  };
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.