Home > Enterprise >  React, complex useState syntax confusion
React, complex useState syntax confusion

Time:07-06

I have a function in useState that I'm having a hard time understanding, how it's working. In short, where's the body of the function setSelectedAccount. Following are the places in code:

  1. In app.jsx inside useState hook:

    const[selectedAccount, setSelectedAccount] = useState({});
    
  2. In app.jsx in render method inside a component being used:

    <Account
      setSelectedAccount = {setSelectedAccount}
      //more code
    
  3. Inside another file Account.jsx (component):

    const FormObserver = props => {
       let {accounts, setSelectedAccount, setFormvalues} = props;
       //more code
    
  4. Inside Account.jsx in useEffect hook:

    useEffect(() =>
      setSelectedAccount(
         find(accounts.data, account => values.selectAccount === account.id)
      );
    
      values.varX = "";
    }, [values.selectAccount]);
    

Summary: selectAccount is just value from a dropdown.

Question: where is the body of the method setSelectedAccount that sets SelectedAccount values? Is find method inside the useEffect hook the body of the setSelected function?

CodePudding user response:

There is no body, basically this

 setSelectedAccount(
     find(accounts.data, account => values.selectAccount === account.id)
  );

is the same code as:

 setSelectedAccount(() => {
  return find(accounts.data, account => values.selectAccount === account.id)();
 });

It's just shorter to return find because it returns a function anyway.

I don't know what find is but based on the structure it is a function that returns a function, probably looks like this (lodash fp probably):

const find = (list, cb) => () => {}
  • Related