I am developing a skeleton for an application using the react.js
with actual scenarios until the APIs are being developed.
The local variable called accountType
generates a dropdown in the Form
component, is not getting updated.
If I am console logging inside the useEffect
function then its working, but the variable is not getting updated.
export default () => {
let accountTypes: Array<Object> = [];
...
useEffect(() => {
accountTypes = [
{
value: 1,
label: 'Developer',
},
{
value: 2,
label: 'Personal',
},
{
value: 3,
label: 'Professional',
},
];
}, []);
console.log(accountTypes);
return (
<Form accountTypes={accountTypes}>
...
</Form>
)
});
Not sure how to handle it as this is my first try on any frontend framework.
3
Answers
What’s going on here is that on first render, useEffect run, setting your variable, but then on subsequent runs, it gets set back to an empty array. I personally, would set it up like this:
However, if you expect to need to edit
accountTypes
, I would set it up like this:Below is the example how to use useState hook. you can use take the reference from below code.
PROBLEM : You are getting [] in accountTypes because the UI is rendered before the UseEffect and since its local variable you can not see updated variable in console.log.
The answer given by Risheekant Vishwakarma is correct.
Here is another approach using USEREF to achieve what you want.