Search code examples
reactjsreact-hookslocal-variables

ReactJs: useEffect is not updating the local variable


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>
    )
});

enter image description here

Not sure how to handle it as this is my first try on any frontend framework.


Solution

  • Below is the example how to use useState hook. you can use take the reference from below code.

    import React from "react";
    export default function App() {
      const [accountTypes, setAccountTypes] = React.useState([]);
    
      React.useEffect(() => {
        setAccountTypes([
          {
            value: 1,
            label: "Developer"
          },
          {
            value: 2,
            label: "Personal"
          },
          {
            value: 3,
            label: "Professional"
          }
        ]);
      }, []);
    
      console.log(accountTypes);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }