import { FC, useEffect, useState } from 'react';
import {Element} from '../types';
import ElementView from './ElementView';

const ElementList: FC = () => {
  const [elements, setElements] = useState<Element[]>([]);

  useEffect(() => {
    const initialElements: number[] = [1, 2, 3, 4];

    const elementStateString = localStorage.getItem('elementState');
    if (elementStateString != null) {
        setElements(JSON.parse(elementStateString));
        return;
    }

    const fetchElements = async () => {
      const elems: Element[] = [];
      
      for (const elemId of initialElements) {
        const response = await fetch(`/api/element/${elemId}`);
        const elem: Element = await response.json();
        elems.push(elem);
      }

      localStorage.setItem('elementState', JSON.stringify(elems));
      setElements(elems);
    };

    fetchElements().catch(console.error);
  }, []);

  useEffect(() => {
    if (elements.length != 0) {
        localStorage.setItem('elementState', JSON.stringify(elements));
    }
  }, [elements])

  return (
    <>
    {elements.map(elem => <ElementView key={elem.id} element={elem} />)}
    </>
  );
};

export default ElementList;
