Dialog popup not displaying rowData react - reactjs

I am new to react and working on a table with MaterialUI. It is an editable table and I am trying to have an icon that returns a dialog box. I can get the dialog returned but when trying to pass through the rowData I get nothing. I have tried useState (probably using it wrong) and also trying to pass the data as a parameter.
See code below
export default function MaterialTableDemo() {
const [state, setState] = React.useState({
columns : [
{ title: "Program", field: "Program", defaultFilter: "Program" },
{
title: 'Program Type',
field: 'ProgramType',
lookup: { 1: 'Assignment', 2: 'Auto', 3: 'Default' },
},
],
data : [
{ Program: 'Program', ProgramType: 1 },
{ Program: 'Program 2', ProgramType: 3 },
],
});
function handleOnClose() {
setOpen(false)
}
function handleOnOpen() {
setOpen(true)
//console.log(rowData);
}
const [open, setOpen] = React.useState(false);
const [close, setClose] = React.useState();
return (
<div className="section">
<h6>filtering</h6>
<MaterialTable
columns={state.columns}
icons={tableIcons}
data={state.data}
dataIcon = {rowData => {
return (
console.log(rowData),
React.useState(rowData)
)
}}
detailPanel={rowData => {
return (
console.log(rowData),
<div>
<h2>Expired Time </h2> <br></br>
<span>{rowData.ExpireDate}</span>
<br></br>
<Popup modal trigger={<button>Edit </button>}>
{close => <Content close={close} />}
</Popup>
</div>
)
}}
options={{
filtering: true
}}
actions={rowData => {
return (
console.log(rowData)
)},
[
{
icon: tableIcons.Star,
tooltip: 'Popup to Edit',
onClick: (event, handleOnOpen)
},
]}
title="Program"
editable={{
onRowAdd: newData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setState(prevState => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
if (oldData) {
setState(prevState => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setState(prevState => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}
}
/>
<Dialog
open={open}
onClose={handleOnClose}
aria-labelledby="draggable-dialog-title"
>
<DialogTitle id="draggable-dialog-title">Edit Program</DialogTitle>
<DialogContent>
<DialogContentText>
Edit Program
</DialogContentText>
<div className="group">
{" "}
<label label for="ProgramCode"><b> Program: </b></label>
<input align="right" type="ProgramCode" placeholder="Enter Program Code" align="right" width="300" required></input>
</div>
<div className="group">
{" "}
<label for="ProgramTypeCode"><b> Program Type: </b></label>
<input type="ProgramTypeCode" placeholder="Enter Program Type" align="right" width="300" name="CPTC" required></input>
</div>
<br></br>
<button>Save</button>
</DialogContent>
</Dialog>
<br></br>
</div>
);
}

Related

Can't filter data on users select option and render it onclick

I am making a form web application in react.js with select options(using material UI) and an onclick button. The problem is that I don't know how to filter the data from my local API so that when the user chooses an option on the UI they will then have that specific data from the API rendered when they press submit.
Currently, I have mapped all the data to the submit button:
Here is the data from the API:
If for example the user just selects Entry Point and clicks submit then I just want all of the data for Entry Point to be shown.
This is how I am rendering the data in react:
const initialData = ({
first: "",
second: "",
third: "",
fourth: ""
});
const Form = () =>{
const [Data, updateData] = React.useState(initialData);
const [users, setUsers] = useState([]);
const handleChange = (e) => {
updateData({
...Data,
[e.target.name]: e.target.value
});
};
const handleAutocompletefirstChange = (e, value) => {
updateData({
...Data,
first: value,
});
};
const handleAutocompletesecondChange = (e, value) => {
updateData({
...Data,
second: value
});
};
const handleAutocompletethirdChange = (e, value) => {
updateData({
...Data,
third: value
});
};
const handleAutocompletefourthChange = (e, value) => {
updateData({
...Data,
fourth: value
});
};
const options = ['Entry Point', 'Exit Point', 'MTOW (TONNES)', '5 to 40', 'More than 40 and upto 120', 'More than 120 and upto 250', 'More than 250 and upto 350', 'More than 350 and upto 450', 'More than 450']
const fetchData = async (e) => {
setSpinner(true);
e.preventDefault();
const res = await fetch('http://localhost:3000/getdata_withQuery');
console.log(res);
const data = await res.json();
setUsers(data);
console.log(Data);
const newData = await fetch('/api', {
method: 'POST',
headers: {
'content-type' : 'application/json',
'Accept' : 'application/json'
},
body: JSON.stringify({
name: Data.initialData
})
})
.then(res => res.json(setSpinner(false)));
console.log(newData);
}
return (
<div className='container'>
<Content>
<div className='features'>
<div className='buttons'>
<h1>Fill in Details</h1>
<form>
<div className='ComboBox'>
<div style={{marginLeft:'0%', marginTop: '0px'}}>
<Autocomplete
name='initialData'
onChange={(event, value) => handleAutocompletefirstChange(event, value)}
options={options}
style={{ width: 300 }}
renderInput={(params) =>
<TextField {...params} label="select" variant="outlined" name="first" onChange={handleChange} />}
/>
</div>
<br/>
<div style={{marginLeft:'0%', marginTop: '0px'}}>
<Autocomplete
name='initialData'
onChange={(event, value) => handleAutocompletesecondChange(event, value)}
options={options}
style={{ width: 300 }}
renderInput={(params) =>
<TextField {...params} label="select" variant="outlined" name="second" onChange={handleChange}/>}
/>
</div>
<br/>
<div style={{marginLeft:'0%', marginTop: '0px'}}>
<Autocomplete
name='initialData'
onChange={(event, value) => handleAutocompletethirdChange(event, value)}
options={options}
style={{ width: 300 }}
renderInput={(params) =>
<TextField {...params} label="select" variant="outlined" name="third" onChange={handleChange}/>}
/>
</div>
<br/>
<div style={{marginLeft:'0%', marginTop: '0px'}}>
<Autocomplete
name='initialData'
onChange={(event, value) => handleAutocompletefourthChange(event, value)}
options={options}
style={{ width: 300 }}
renderInput={(params) =>
<TextField {...params} label="select" variant="outlined" name="fourth" onChange={handleChange}/>}
/>
</div>
<br/>
</div>
<div className='btn'>
<Button type="submit" variant="primary" onClick={(e) => fetchData(e)}>Submit</Button>{' '}
<Button type='clear' variant="danger">Clear</Button>{' '}
</div>
</form>
<div className='data'>
{users.map((item) => (
<div className='map_Data'>
<ol key={item.ENTRY_POINT1}>
Entry_Point: { item.ENTRY_POINT1 }
<br />
Exit_Point: { item.EXIT_POINT1 }
<br />
Route_Point: { item.RoutePoint }
<br />
Distance_Nm: { item.DistanceNm }
<br />
MTOW (TONNES): { item.Distance_km }
<br />
fourty: {item.fourty}
<br/>
onehundredtwenty: {item.onehundredtwenty}
<br/>
twohundredfifty: {item.twohundredfifty}
<br/>
threehundredfifty: {item.threehundredfifty}
<br/>
fourhundredfifty: {item.fourhundredfifty}
<br/>
morefourhundredfifty: {item.morefourhundredfifty}
</ol>
</div>
))}
</div>
</div>
</div>
</div>
)
}
In my Node API I made this query to pull the data from my MSSQL database:
async function getdata_withQuery() {
try {
let pool = await sql.connect(config);
let res = await pool.request().query("select [ENTRY_POINT1], [EXIT_POINT1], [RoutePoint], [DistanceNm], ROUND([Distance_km],0) AS [Distance_km], ROUND([Distance_km] * 0.44, 0) AS [fourty], ROUND([Distance_km] * 0.58, 0) AS [onehundredtwenty], ROUND([Distance_km] * 0.88, 0) AS [twohundredfifty], ROUND([Distance_km] * 1, 0) AS [threehundredfifty], ROUND([Distance_km] * 1.14, 0) AS [fourhundredfifty], ROUND([Distance_km] * 1.30, 0) AS [morefourhundredfifty] from [dbo].['Data File$']");
return res.recordsets;
} catch (error) {
console.log(" mathus-error :" + error);
}
}
For more information here is the repo for my form web-app (src/components/ComboBox.js):
https://github.com/N00rAhmed/Avtag-Form/tree/working-branch
Also here is my Node.js Api: https://github.com/N00rAhmed/flytag-api
I have tried using the filter method in react.js and I was able to make a search filter using a text field, but not using select options because I kept on coming across errors which i didn't understand. I also tried doing an onclick handler on the select option but I quickly realised that wouldn't work.
you just get the data once, then give the array to jsx based on your search
this is a function that returns an array based on the given array and the proprety that you want to filter with
export const findWithProp = (array, prop) => {
var arrayToReturn =[];
if (prop=== "ALL") {return array;}
else {
array.forEach((element) => {
if (element[prop]){arrayToReturn.push(element);}
});
}
return arrayToReturn;};
so in your useEffect each time the value of the filter change let's call it "newValue"
const[newValue,setNewValue] = useState("");
you can update the arrayToShow and give it to jsx
const[arrayToShow,setArrayToShow] = useState([]);
useEffect(()=>{
setArrayToShow(findWithProp (users,newValue))
},[newValue])
in your jsx :
{
arrayToShow.map(element=>{
return(
// your logic
)
}

After editing data, redux cannot read id

i have a problem.
I use a form to edit my data, then when i want to see edited data, i get an ×
TypeError: Cannot read properties of undefined (reading 'id')
Pointing at my
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
Which is used to display data.
After refreshing the site (F5) it works, so i assume that the redux has problem with reading edited data for the first time, altough it do work with adding new data. anyone know what i can do?
My UserEditForm:
const UserEditForm = () => {
let { id } = useParams();
const { user } = useSelector((state) => state.user);
const [state, setState] = useState({
name: "",
birthday: "",
img: "",
});
const [error, setError] = useState("");
console.log(id);
let history = useHistory();
let dispatch = useDispatch();
const { name, birthday, img } = state;
useEffect(() => {
dispatch(getSingleUser(id));
}, []);
useEffect(() => {
if (user) {
setState({ ...user });
}
}, [user]);
const handleInputChange = (e) => {
let { name, value } = e.target;
setState({ ...state, [name]: value });
};
const handleSubmit = (e) => {
dispatch(updateUser(state, id));
history.push("/");
setError("");
};
return (
<div>
<Button
style={{ width: "100px", marginTop: "20px" }}
variant="contained"
color="secondary"
onClick={() => history.push("/")}
>
Go Back
</Button>
<h2>Edit User</h2>
{error && <h3 style={{ color: "red" }}>{error}</h3>}
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
id="standard-basic"
label="Name"
value={name || ""}
name="name"
type="text"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="birthday"
name="birthday"
value={birthday || ""}
type="birthday"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="img"
value={img || ""}
name="img"
type="number"
onChange={handleInputChange}
/>
<Button
style={{ width: "100px" }}
variant="contained"
color="primary"
type="submit"
onChange={handleInputChange}
>
Update
</Button>
</form>
</div>
);
};
export default UserEditForm;
My UserList component:
const UserList = ({ users, history }) => {
const dispatch = useDispatch();
const fetchUsers = async () => {
const response = await axios
.get("http://localhost:3000/characters")
.catch((err) => {
console.log("Err: ", err);
});
dispatch(setUsers(response.data));
};
useEffect(() => {
fetchUsers();
}, []);
console.log(users);
return (
<div>
<button onClick={() => history.goBack()}>...back</button>
<li>
<Link to="/user/add">Add Users</Link>
</li>
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
</div>
);
};
const mapStateToProps = (state) => {
return {
users: state.allUsers.users,
};
};
export default connect(mapStateToProps, null)(UserList);

React Hooks Antd props to update

I`m trying to pass the data from a table component to a form that opens when I press the edit button, I know how to do it with react Class but I'm trying with hooks but I still don't understand how to do it.
Here is an image of the table.
Here is an image of the form.
Index.js
const GestionUsuarios = () => {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const [form] = Form.useForm();
const [visible, setVisible] = useState(false);
const [visibleEdit, setVisibleEdit] = useState(false);
const [users, setUsers] = useState(null);
const [post, setPost] = React.useState(null);
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const columns = [
{
title: 'ID',
dataIndex: 'id',
sorter: true,
key: 'id',
//render: name => `${name.first} ${name.last}`,
//width: '20%',
},
{
title: 'Tipo de usuario',
dataIndex: 'tipo',
filters: [
{ text: 'Administrador', value: '1' },
{ text: 'Supervisor', value: 'super' },
{ text: 'Expedicion Granulado', value: 'expg' },
{ text: 'Expedicion Silo', value: 'exps' },
{ text: 'Lectura', value: 'lectura' },
],
},
{
title: 'Nombre',
dataIndex: 'nombre',
},
{
title: 'Apellido',
dataIndex: 'apellido',
},
{
title: 'Alias',
dataIndex: 'username',
},
{
title: 'Email',
dataIndex: 'email',
},
{
title: 'Action',
key: 'action',
fixed: 'right',
width: 100,
render: (_, record) => (
<div>
<Button
//onClick={() => retrieveConfig(record.id)}
onClick={() => {
setVisibleEdit(true);
}}
icon={<EditOutlined />}
/>
</div>
),
},
{
title: '',
key: 'action2',
fixed: 'right',
width: 100,
render: (_, record) => (
<Button
//onClick={() => deleteConfig(record.id, record.test_type)}
onClick={() => deleteRoute(record.id)}
icon={<DeleteOutlined />}
/>
),
},
];
useEffect(() => {
fetch('http://localhost:8080/api/usuarios', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
}).then((res) =>
res.json().then((result) => {
setUsers(result);
console.log(result);
})
);
}, []);
const onEdit = (response, id) => {
console.log('USUARIO A editar: ', response);
setVisible(false);
axios
.put(`http://localhost:8080/api/usuarios/${id}`, {
tipo: response.tipo,
nombre: response.nombre,
pass: response.pass,
username: response.username,
apellido: response.apellido,
email: response.email,
})
.then((response) => {
setPost(response.data);
window.location.reload();
});
};
return (
<div>
<Button
onClick={() => {
setVisible(true);
}}
type='primary'
style={{ marginBottom: 16 }}
>
Nuevo usuario
</Button>
<AddForm
visible={visible}
onCreate={onCreate}
onCancel={() => {
setVisible(false);
}}
/>
<EditForm
visible={visibleEdit}
onCreate={onCreate}
onCancel={() => {
setVisibleEdit(false);
}}
/>
<Table
columns={columns}
dataSource={users}
pagination={pagination}
loading={loading}
rowKey={(record) => record.id}
//onChange={this.handleTableChange}
//rowKey="id"
/>
</div>
);
};
export default GestionUsuarios;
EditForm.js
const EditFormUsuarios = ({ visible, onCreate, onCancel, props }) => {
const [form] = Form.useForm();
const [post, setPost] = React.useState(null);
const [userID, setUserID] = useState(null);
const [username, setUsername] = useState('');
const [dataform, setDatosForm] = useState({
id: '',
tipo: '',
nombre: '',
apellido: '',
username: '',
pass: '',
email: '',
});
const handleUserId = (id) => {
console.log('ID seleccionado: ', id);
//setVisible(false);
axios
.get(`http://localhost:8080/api/usuarios/${id}`, {
//.then(response => response.json())
})
.then((result) => {
setUserID(result);
console.log(result);
axios.put(`http://localhost:8080/api/usuarios/${result.id}`, {
tipo: result.tipo,
nombre: result.nombre,
apellido: result.apellido,
username: result.username,
pass: result.pass,
email: result.email,
//.then(response => response.json())
});
});
};
useEffect(() => {
/*if(this.props.item){
const { tipo} = this.props.item
this.setState({ tipo})
}
if(this.props.item){
const { nombre} = this.props.item
this.setState({ nombre})
}
if(this.props.item){
const { apellido} = this.props.item
this.setState({ apellido})
}
if(this.props.item){
const { username} = this.props.item
this.setState({ username})
}
if(this.props.item){
const { pass} = this.props.item
this.setState({ pass})
}
if(this.props.item){
const { email} = this.props.item
this.setState({ email})
}*/
}, []);
return (
<Modal
{...props}
visible={visible}
title='Editar usuario'
okText='Confirmar'
cancelText='Cancelar'
onCancel={onCancel}
onOk={() => {
form
.validateFields()
.then((values) => {
form.resetFields();
onCreate(values);
})
.catch((info) => {
console.log('Validate Failed:', info);
});
}}
>
<Form
form={form}
layout='vertical'
name='form_in_modal'
initialValues={{
modifier: 'public',
}}
>
<Form.Item
name='id'
label='Alias'
rules={[
{
required: true,
message: 'Introduce el alias',
},
]}
// onChange={e => setUsername(e.target.value)}
value={dataform && dataform.id}
></Form.Item>
<Form.Item
name='username'
label='Alias'
rules={[
{
required: true,
message: 'Introduce el alias',
},
]}
onChange={(e) => setUsername(e.target.value)}
value={dataform && dataform.username}
>
<Input />
</Form.Item>
<Form.Item
name='pass'
label='Contraseña'
rules={[
{
required: true,
message: 'Introduce la contraseña',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='nombre'
label='Nombre'
rules={[
{
required: true,
message: 'Introduce el nombre',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='apellido'
label='Apellido'
rules={[
{
required: true,
message: 'Introduce el apellido',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='email'
label='Email'
rules={[
{
required: true,
message: 'Introduce el email',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='tipo'
label='Tipo de usuario'
rules={[
{
required: true,
message: 'Introduce el tipo de usuario!',
},
]}
>
<Input />
</Form.Item>
</Form>
</Modal>
);
};
export default EditFormUsuarios;
from index.js ===> onCreate={onCreate} ?? add the onEdit or related event handling function

Marerial Table select menu is connected to each row?

My Material-Table has a select menu as one of the columns, however when i select one of the options it changes it for all the rows. How can I make the change row specific so that they are not connected to each other? I realize that the event.target.value approach is applied to all of the mapped select menues, I cant figure out how to make it specific to one.
The row in question is the Facility column
const selectData = ["One", "Two", "Three"];
function Table() {
const columns = [
{
title: "Avatar",
render: (rowData) => (
<Avatar
maxInitials={1}
size={40}
round={true}
name={rowData === undefined ? " " : rowData.first_name}
/>
),
},
{ title: "ID", field: "_id", hidden: true },
{ title: "Name", field: "name" },
{ title: "Email", field: "email" },
{ title: "Company", field: "companyID" },
{ title: "Role", field: "role" },
{
title: "Facility",
render: (rowData) => (
<FormControl>
<InputLabel id="demo-mutiple-checkbox-label">Tags</InputLabel>
<Select
labelId="demo-mutiple-checkbox-label"
id="demo-mutiple-checkbox"
multiple
value={items}
onChange={handleChange}
input={<Input />}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{selectData.map((item) => (
<MenuItem key={item} value={item}>
<Checkbox checked={items.indexOf(item) > -1} />
<ListItemText primary={item} />
</MenuItem>
))}
</Select>
</FormControl>
),
},
{ title: "Password", field: "password" },
];
const [data, setData] = useState([]);
const [items, setItems] = useState([]); //table data
const handleChange = (event) => {
setItems(event.target.value);
};
return (
<div>
<MaterialTable
title="Users"
columns={columns}
data={data}
icons={tableIcons}
editable={{
onRowUpdate: (newData, oldData) =>
new Promise((resolve) => {
handleRowUpdate(newData, oldData, resolve);
}),
onRowAdd: (newData) =>
new Promise((resolve) => {
handleRowAdd(newData, resolve);
}),
onRowDelete: (oldData) =>
new Promise((resolve) => {
handleRowDelete(oldData, resolve);
}),
}}
/>
</div>
);
}
I think you should define an editComponent in the Facility column, by doing so you will able to modify the value of the current rowData and not just the items variable which is being set as valuein the select component and therefore shown in every row.
Here is an example:
const tableColumns = [
{ title: "Client", field: "id" },
{ title: "Name", field: "name" },
{
title: "Choose a Fruit",
field: "fruit",
editComponent: ({ value, onChange }) => (
<select onChange={(e) => onChange(e.target.value)}>
<option selected value={value}>
{value}
</option>
{fruitsList.map(
(item) =>
item !== value && (
<option key={item} value={item}>
{item}
</option>
)
)}
</select>
)
}
];
Hope that works for you! Full code and sandbox here.

React.js: How to pass onchange value of listbox to function?

I'm trying to pass value from the onchange of listbox to a function called handleOnChange
In the handleOnChange function, I set the value to state (array)
However, I get an error when I try to add curly braces when enclosing selected
Eventually, I will be trying to pass this as a json request
ProfileMaintenancePage.js
const [selectedModules, setSelectedModules] = useState([]);
const handleOnChange = (selected) => {
console.log("selected " + selected)
setSelectedModules(selected)
};
return (
<DualListBox
options={ newOptionsListbox }
selected={ selectedModules }
onChange={ handleOnChange }
showHeaderLabels={ true }
disabled={ disabled }
/>
)
The value is passed correctly to the handleOnChange
Is this the correct way to set this on the state?
How can I access this from the state?
TIA
EDIT:
Full page code of ProfileMaintenancePage.js
import React, {useState, useCallback, useEffect, useRef} from 'react';
import { MDBCard, MDBCardBody, MDBBreadcrumb, MDBBreadcrumbItem, MDBDataTable, MDBCol, MDBBtn } from 'mdbreact';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import BootstrapTable from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import 'react-dual-listbox/lib/react-dual-listbox.css';
import DualListBox from 'react-dual-listbox';
import ProfileMaintenanceService from '../../services/ProfileMaintenanceService';
const ProfileMaintenancePage = () => {
const [data, setData] = useState([]);
const [listboxModules, setListboxModules] = useState([]); /* populate modules listbox */
const [selectedModules, setSelectedModules] = useState([]); /* store selected modules */
const [modulesIds, setModuleIds] = useState(''); /* store selected modules */
const [listboxActions, setListboxActions] = useState([]); /* populate modules listbox */
const [name, setName] = useState('');
const [disabled, setDisabled] = useState(false);
const retrieveModulesList = useCallback(() => {
ProfileMaintenanceService.retrieveModulesList()
.then((response) => {
console.log("ProfileMaintenancePage - retrieveModulesList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveModulesList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxModules(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveModulesList catch >>> " + err)
})
});
const retrieveActionsList = useCallback((selectedModules) => {
ProfileMaintenanceService.retrieveActionsList(selectedModules)
.then((response) => {
console.log("ProfileMaintenancePage - retrieveActionsList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveActionsList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxActions(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveActionsList catch >>> " + err)
})
});
useEffect(() => {
retrieveModulesList();
}, []);
/* CLIENT */
const columnsClient = [
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'name',
text: 'Name',
sort: true,
filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'creator',
text: 'Creator',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'creationdate',
text: 'Creation Date',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'lastmodifier',
text: 'Last Modifier',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'lastmodification',
text: 'Last Modification',
sort: true
// filter: textFilter()
},
];
const selectRowClient = {
mode: 'checkbox',
clickToSelect: true,
clickToEdit: false,
hideSelectAll: false,
hideSelectColumn: false,
onSelect: (row, isSelect, rowIndex) => {
}
};
/* Pagination */
const customTotal = (from, to, size) => (
<span className="react-bootstrap-table-pagination-total">
Showing { from } to { to } of { size } Results
</span>
);
const options = {
paginationSize: 4,
pageStartIndex: 0,
alwaysShowAllBtns: true,
hideSizePerPage: true,
firstPageText: 'First',
prePageText: 'Back',
nextPageText: 'Next',
lastPageText: 'Last',
nextPageTitle: 'First page',
prePageTitle: 'Pre page',
firstPageTitle: 'Next page',
lastPageTitle: 'Last page',
showTotal: true,
paginationTotalRenderer: customTotal,
sizePerPageList: [{
text: '5', value: 5
}, {
text: '10', value: 10
}, {
text: 'All', value: data.length
}]
};
/* CLIENT -- end */
const newOptionsListbox = listboxModules.map(({id, module, description}) => ({
id: id,
label: module,
value: id /* temporarily set to id but it should be description */
}))
const newOptionsListbox2 = listboxModules.map(({id, module, description}) => ({
id: "",
label: "",
value: "" /* temporarily set to id but it should be description */
}))
const handleOnChange = (selected) => {
console.log("selected " + selected)
setSelectedModules( selected )
// setModuleIds(selectedValues)
retrieveActionsList()
};
const addProfile = () => {
setDisabled(false);
};
return (
<div>
<MDBCard className="mb-2">
<MDBCardBody id="breadcrumb" className="d-flex align-items-center justify-content-between">
<MDBBreadcrumb>
<MDBBreadcrumbItem>Administrator</MDBBreadcrumbItem>
<MDBBreadcrumbItem active>Profile Maintenance</MDBBreadcrumbItem>
</MDBBreadcrumb>
</MDBCardBody>
</MDBCard>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCol md="12">
<form className="form-horizontal form-group">
<div className="text-left mt-2">
<MDBBtn color="indigo" type="button" onClick={() => { addProfile(); }}>Add</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Delete</MDBBtn>
</div>
</form>
</MDBCol>
<BootstrapTable
keyField='id'
hover
data={ '' }
columns={ columnsClient }
filter={ filterFactory() }
selectRow={ selectRowClient }
noDataIndication="No record(s) found."
pagination={ paginationFactory(options) }
/>
</MDBCardBody>
</MDBCard>
<MDBCol md="6">
<br />
<label htmlFor="name" className="dark-grey-text">
Name
</label>
<input type="text" id="name" className="form-control"
value={name} onChange={e => setName(e.target.value)} disabled={disabled} />
</MDBCol>
<MDBCol md="12">
<br />
<label htmlFor="entities" className="dark-grey-text">
Modules
</label>
<DualListBox
options={ newOptionsListbox }
selected={ selectedModules }
onChange={ handleOnChange }
showHeaderLabels={ true }
disabled={ disabled }
/>
<br />
<label htmlFor="entities" className="dark-grey-text">
Actions
</label>
{/* <DualListBox
options={ newOptionsListbox2 }
selected={ selectedModules }
onChange={ onChange }
showHeaderLabels={ true }
disabled={ disabled }
/> */}
<br />
</MDBCol>
<MDBCol md="12">
<form className="form-horizontal form-group">
<div className="text-right mt-2">
<MDBBtn color="indigo" type="button" onClick={() => {}}>Export</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Cancel</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Save</MDBBtn>
</div>
</form>
</MDBCol>
</MDBCardBody>
</MDBCard>
</MDBCardBody>
</MDBCard>
</div>
);
}
export default ProfileMaintenancePage;
Issue:
When using this function, I can't seem to access the value of the state specifically selectedModules
const retrieveActionsList = useCallback((selectedModules) => {
ProfileMaintenanceService.retrieveActionsList(selectedModules)
.then((response) => {
console.log("ProfileMaintenancePage - retrieveActionsList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveActionsList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxActions(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveActionsList catch >>> " + err)
})
});
I think what you want is an array in the state, but you always overwrite your array with one element.
So selectedModuels woud be <DualListBox /> always.
If you want to push it, you could use:
newState = selectedModules.slice();
newState.push(selected);
setSelectedModules(newState);

Resources