I'm trying to set default value to datalist using useEffect.
Tried to set it (line 16) with setSelectedEmployee(employees[0].id);
I also tried (line 64) to set default value with, no success.
value={employees[0].name}
Here is working example: https://codesandbox.io/s/prefill-list-73c4sd
Any help would be highly appreciated.
I believe this is what you're looking for:
https://codesandbox.io/s/prefill-list-forked-hqowhz?file=/src/App.js
What we've done:
We added a separate useEffect
hook that has a dependency on employees
. Every time employees
changes, it'll take the first value and set the name. Your filter method uses the name, so that's how I structured it.
The code (here):
import React, { useState, useEffect } from "react";
import DataService from "./services/DataService";
import "./styles.css";
import "antd/dist/antd.css";
import { Modal, Button } from "antd";
export default function App() {
const [employees, setEmployees] = useState([]);
const [selectedEmployee, setSelectedEmployee] = useState("");
const [isModalVisible, setIsModalVisible] = useState(false);
useEffect(() => {
DataService.getUsersData().then((res) => {
setEmployees(res.data);
//setSelectedEmployee(employees[0].id);
});
}, []);
useEffect(() => {
// We can set the first one as selected here
employees.length && setSelectedEmployee(employees[0]?.name);
}, [employees]);
const handleChange = (event) => {
setSelectedEmployee(event.target.value);
};
const clear = (event) => {
event.target.value = "";
};
const showModal = () => {
setIsModalVisible(true);
};
const handleOk = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
const selectedEmployeeId =
selectedEmployee.trim().length > 0
? employees.find((employee) => employee.name === selectedEmployee)?.id ||
""
: "";
//console.log(selectedEmployee, selectedEmployeeId);
return (
<div className="App">
<h1>Choose Employee From List</h1>
<table id="tblEmployees">
<tbody>
<tr>
<td>
<label htmlFor="employeeName"> Employee Name</label>
</td>
<td>
<input
id="employeeName"
list="listOfEmployees"
onChange={handleChange}
onClick={clear}
onFocus={clear}
value={selectedEmployee}
></input>
<datalist id="listOfEmployees">
{employees && employees.length > 0 ? (
employees.map((employee) => {
return (
<option key={employee.id} value={employee.name}>
{employee.name}
</option>
);
})
) : (
<div>Data loading in progress...</div>
)}
</datalist>
</td>
</tr>
<tr>
<td>
<label htmlFor="employeeId"> Employee ID</label>
</td>
<td>
<input id="employeeId" defaultValue={selectedEmployeeId}></input>
</td>
</tr>
</tbody>
</table>
<Button type="primary" onClick={showModal}>
Open modal
</Button>
<Modal
title="Basic Modal"
visible={isModalVisible}
onOk={handleOk}
onCancel={handleCancel}
>
<p>Chosen Employee ID {selectedEmployeeId}</p>
<p>Some contents...</p>
</Modal>
</div>
);
}