import React, {useEffect,useState} from 'react'
import axios from 'axios';
import {Link} from 'react-router-dom';

export default function Read() {
    //get data
    const getData=()=>{
	axios.get('http://83.223.94.182:65535/entities/info')
	    .then((response)=>{
		setApiData(response.data);
	    });
    };
    //create state containing incoming data array
    const [apiData,setApiData]=useState([]);
    //useEffect Hook, cos we need data when app loads
    useEffect(()=>{
	//console.log('Read calls useEffect()');
	getData();
    },[]);
    //handle update button
    const setData=(data)=>{
	console.log('data: '+data);
    };
    //handle delete button
    const onDelete=(id)=>{
	console.log('read:onDelete() id: '+id);
	getData()
    };
    return (
	<div>
	    <h1>Read</h1>
	    <table>
		<thead>
		    <tr>
			<th>Id</th>
			<th>Name</th>
			<th>Update</th>
			<th>Delete</th>
		    </tr>
		</thead>
		<tbody>
		    {apiData.map((value,key) => {
			//console.log('key: '+key+', value: '+value);
			return (
			    <tr
				key={key}
			    >
				<td>{value[0]}</td>
				<td>{value[1]}</td>
				<td>
				    <Link to='/update'>
					<button
					    type="button"
					    onClick={()=>setData(data)}
					>
					    Update
					</button>
				    </Link>
				</td>
				<td>
				    <button
					type="button"
					onClick={()=>onDelete(data.id)}
					>
					    Delete
					</button>
				</td>
			    </tr>
			);
		    })}
		</tbody>
	    </table>
	</div>
    );
};
