Home > Blockchain >  ReactJS - Passing data as props that I've just extracted from Child Component
ReactJS - Passing data as props that I've just extracted from Child Component

Time:07-06

So i have just used the saveSavingGoalHandler to extract some Data from a child component < SavingsGoal />.. i have it saved in SaveGoalData and when i run the Console.log() i get the correct string.

The issue is i now need to pass it down to the other component < TransactionFeed />. When i do savingGoalId={SaveGoalData} i get "SaveGoalData" is undefined..

my first thought was to us let SaveGoalData = "" outside the component then have SaveGoalData = SavingsGoalID in the function but i just get undefined as it would run the empty string before it gets filled..

any ideas???

    const saveSavingGoalHandler = (SavingsGoalID) => {
    let SaveGoalData = SavingsGoalID;
    console.log(SaveGoalData);
  };

  return (
    <div className="App">
      <GetAccountName />
      <TransactionFeed
        accountUID={AccountID}
        defCategory={DefCategory}
        savingGoalId={SaveGoalData} <--- Is Undefined
      />
      <SavingsGoal
        accountUID={AccountID}
        defCategory={DefCategory}
        onSaveSavingGoal={saveSavingGoalHandler}
      />
    </div>
  );

CodePudding user response:

You are correct, you should be using let SaveGoalData outside of saveSavingGoalHandler since that let is available only in the scope of saveSavingGoalHandler.

I recommend using setState({ SaveGoalData: SavingsGoalData }) inside saveSavingGoalHandler and reading the SaveGoalData from state in TransactionFeed props.

Side note: this seems like anti-pattern considering that data flow in React should be unidirectional.

CodePudding user response:

const Parent = () => {
  const [saveGoalData, setSaveGoalData] = useState()
   const saveSavingGoalHandler = (SavingsGoalID) => {
    setSaveGoalData(SavingsGoalID)
  };

  return (
    <div className="App">
      <GetAccountName />
      <TransactionFeed
        accountUID={AccountID}
        defCategory={DefCategory}
        savingGoalId={saveGoalData}
      />
      <SavingsGoal
        accountUID={AccountID}
        defCategory={DefCategory}
        onSaveSavingGoal={saveSavingGoalHandler}
      />
    </div>
  );
  • Related