0

check out the following block of code:

const [doj, setDoj] = useState(Date);
const handleEmployeeNumberChange = async (e, value, name) => {
        if (name === 'Employee Number') {
            const employee = await employeeServices.getByNumber(value);
            formik.setFieldValue('Employee Name', employee['Personal Information']['Employee Name']);
            formik.setFieldValue('Date of Joining', employee.Company['Date of Joining']);
            setDoj(new Date(employee.Company['Date of Joining']));
            console.log(new Date(employee.Company['Date of Joining']));
            console.log(doj);
            const element = { target: { name, value } };
            formik.handleChange(element);
        }
    };

So what im trying to do is, when the employee number changes, i want to update the state of a variable by the name of 'doj'. but That line isnt working for some reason. The output is shown below:

enter image description here

As you can see the second console log is the value of doj, which is its default value, which is why setDoj didnt work for some reason. Please Help!

Vedant Shah
  • 149
  • 7
  • Please show all relevant code: what does `setDoj` do and how does it update the `doj` variable? For readability it would make more sense to have `setDoj` return some value so you can use it like: `doj = setDoj(...)`. – Jasper Apr 14 '22 at 11:22
  • `useState(Date)` should almost certainly be `useState(new Date())`, unless you really want `doj` to be a **string**. When you call `Date` without `new`, it returns a string. Re the call to `setDoj`: What value does `employee.Company['Date of Joining']` give you? – T.J. Crowder Apr 14 '22 at 11:23
  • 2
    Also, you seem to be expecting `doj` to get updated immediately. That doesn't happen, see [this question's answers](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately). – T.J. Crowder Apr 14 '22 at 11:25
  • 1
    Probably a duplicate of https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately. – T.J. Crowder Apr 14 '22 at 11:25
  • @T.J.Crowder Youre right, i was expecting the change to show up immediately which is wrong, I apologize for my mistake, and for wasting your time. – Vedant Shah Apr 14 '22 at 11:39
  • @VedantShah - No worries! I'm glad it was something simple. :-) – T.J. Crowder Apr 14 '22 at 12:01

0 Answers0