skip to Main Content

I have a list in page.js and I need the contents of the list in another component which is loaded in page.js:

var accounts = [];
...
<div className="main">
    <LeftPanel accounts={accounts}/>
</div>

accounts is a list of the following objects:

{
    uid: some_uid,
    email: account_email
}

LeftPanel accepts accounts as a prop:

export default function LeftPanel({accounts}) {
...
<div>
   {accounts.map(account => (
       <p key={account.uid}>{account.email}</p>
   ))}
</div>
...
}

As accounts are retrieved a I do accounts.push to update accounts. I would like for LeftPanel to update the accounts. How can I update the list of accounts in LeftPanel as accounts is updated in page.js?

I thought using states for accounts and using setAccounts may solve the issue as they invoke a rerender, but it did not.

2

Answers


  1.    const App = () => {
      const [accounts, setAccounts] = useState([{ email: "test", uid: 1 }]);
    
      const updateAccountData = () => {
        setAccounts((prev) => [...prev, { email: "test1", uid: 2 }]);
      };
      return (
        <div>
          <button onClick={updateAccountData}>Update data</button>
          <LeftPanel accounts={accounts} />
        </div>
      );
    };
    

    you can handle with state for updating the data

    Login or Signup to reply.
  2. Maybe you can try adding key in LeftPanel components in page.js. So when there’s a changes in accounts size, LeftPanel will re-render the component.

    var accounts = [];
    ...
    <div className="main">
        <LeftPanel key={accounts.length} accounts={accounts}/>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search