list to tree

This commit is contained in:
Фролов 2021-04-16 15:49:35 +05:00
parent 1800f15c8e
commit b1d73e33b9

View File

@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import { useState, useEffect } from 'react';
import { WellService } from '../services/api'
import Loader from '../components/Loader'
import { Table } from 'antd';
import { Table, TreeSelect } from 'antd';
import { useHistory } from 'react-router-dom'
const columns = [
@ -27,16 +27,58 @@ const columns = [
},
];
// const groupBy = (table, key) => {
// return table.reduce((rv, item) => {
// rv[item[key]] = rv[item[key]] || []
// rv[item[key]].push(item);
// return rv;
// }, []);
// };
const groupBy = (table, ...keys) => {
let key = keys[0]
let groups = table.reduce((rv, item) => {
let keyValue = item[key]
let group = rv.find(o=>o.title === keyValue)
if(!group)
{
group = {
title: keyValue,
value: keys.length === 1 ? item : `${key} ${keyValue} ${item['id']}`,
selectable: keys.length === 1,
children:[]}
rv.push(group)
}
if(keys.length > 1)
group.children.push(item);
return rv;
}, []);
if(keys.length > 1){
for(let group of groups){
group.children = groupBy(group.children, ...keys.slice(1))
}
}
return groups
};
export default function Wells(props){
const [wells, setWells] = useState([])
const [wellsTree, setWellsTree] = useState([])
const [loader, setLoader] = useState(false)
const history = useHistory()
let updateWellsList = async () => {
setLoader(true)
try{
var newWells = (await WellService.get()).map(w =>{return {key:w.id, ...w}})
let newWells = (await WellService.get()).map(w =>{return {key:w.id, ...w}})
let wellsTree = groupBy(newWells, 'deposit', 'cluster', 'caption')
console.log(wellsTree)
setWells( newWells )
setWellsTree(wellsTree)
}
catch(e){
console.error(`${e.message}`);
@ -46,16 +88,27 @@ export default function Wells(props){
useEffect(()=>{updateWellsList()}, [])
const onChange = (value) =>{
;
}
return(<>
<h2>Wells</h2>
<Table
dataSource={wells}
columns={columns}
onRow={(record, rowIndex) => {
onRow={(record) => {
return {
onClick: event => {history.push(`well/${record.id}`)},
};
}}/>
<TreeSelect
style={{ width: '100%' }}
placeholder="Please select"
treeData={wellsTree}
treeDefaultExpandAll
onChange={onChange}
/>
{loader&&<Loader/>}
</>)
}