0

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.

2
  • Can you elaborate more? What default value? Do you mean setting the default selected value for the input field? Commented Feb 20, 2022 at 7:16
  • Yes Joel, I want to set default value from input field, which is populated from datalist. Commented Feb 20, 2022 at 7:49

1 Answer 1

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, that's the what I'm looking for. Thanks! But somehow I hoped that there is a way to set value directly in the useEffect hook. I'm wondering why I can't access to employee array since it is already acquired via setEmployees method?
I think this is what you mean. Let me know. :) I've updated my answer.
That's it, thanks! :) I didn't know that's possible to use twice useEffect hook in the component.
It's actually recommended to isolate concerns with multiple hooks. It also avoids stale state, as the state variable won't update until a rerender, and with an empty dependency array it'll never rerun that logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.