import React, { useState, useEffect } from ‘react’;
import axios from ‘axios’;
const MoveItems = () => {
const [leftItems, setLeftItems] = useState([]);
const [rightItems, setRightItems] = useState([]);
const [selectedLeftItems, setSelectedLeftItems] = useState([]);
const [selectedRightItems, setSelectedRightItems] = useState([]);
useEffect(() => {
// Fetch data from REST service
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await axios.get(‘YOUR_REST_SERVICE_URL’);
const data = response.data;
setLeftItems(data.leftItems);
setRightItems(data.rightItems);
} catch (error) {
console.error(‘Error fetching data:’, error);
}
};
const moveRight = () => {
const updatedLeftItems = leftItems.filter(item => !selectedLeftItems.includes(item));
const updatedRightItems = rightItems.concat(selectedLeftItems);
setLeftItems(updatedLeftItems);
setRightItems(updatedRightItems);
saveData(updatedLeftItems, updatedRightItems);
};
const moveLeft = () => {
const updatedRightItems = rightItems.filter(item => !selectedRightItems.includes(item));
const updatedLeftItems = leftItems.concat(selectedRightItems);
setRightItems(updatedRightItems);
setLeftItems(updatedLeftItems);
saveData(updatedLeftItems, updatedRightItems);
};
const saveData = async (leftItems, rightItems) => {
try {
await axios.post(‘YOUR_REST_SERVICE_URL’, { leftItems, rightItems });
console.log(‘Data saved successfully’);
} catch (error) {
console.error(‘Error saving data:’, error);
}
};
const handleLeftSelectChange = (event) => {
const selectedValues = Array.from(event.target.selectedOptions, option => option.value);
setSelectedLeftItems(selectedValues);
};
const handleRightSelectChange = (event) => {
const selectedValues = Array.from(event.target.selectedOptions, option => option.value);
setSelectedRightItems(selectedValues);
};
return (
<div>
<div>
<h2>Left Items</h2>
<select multiple value={selectedLeftItems} onChange={handleLeftSelectChange}>
{leftItems.map((item, index) => (
<option key={index} value={item}>{item}</option>
))}
</select>
</div>
<div>
<button onClick={moveRight}>></button>
<button onClick={moveLeft}><</button>
</div>
<div>
<h2>Right Items</h2>
<select multiple value={selectedRightItems} onChange={handleRightSelectChange}>
{rightItems.map((item, index) => (
<option key={index} value={item}>{item}</option>
))}
</select>
</div>
</div>
);
};
export default MoveItems;