0

I am still learning about React and the proper ways to use it so I apologize if the issue is simple. My issue here is that I've initialized a state array meant to hold the values of the users inputs. However, upon clicking the button that will add all the necessary objects, it does nothing for the first click. The second click will properly add all objects to the array. I believe this has to do with the fact the input fields are rendered after the function initially loads but I am not sure. Thank you.

import React, { Fragment, useState } from 'react';
import IncomeField from './IncomeField';

export default function BudgetPage() {
  let [newField, setNewField] = useState(1);
  let [graphData, setGraphData] = useState([]);

  let computeData = () => {
    for (let i = 0; i < newField; i++) {
      // Grab Input and Data
      let label = document.getElementById('income-label-' + i).value;
      let data = document.getElementById('income-data-' + i).value;
      setGraphData((graphData) => [
        ...graphData,
        { label: label, value: data },
      ]);
      console.log(graphData);
    }
  };
  return (
    <Fragment>
      <h2 className='brand-title'>Visual Dollar</h2>
      <div className='budget-input-wrapper'>
        <h3 className='question-header'>What are all your income streams?</h3>
        {[...Array(newField)].map((_, i) => (
          <IncomeField
            key={'income-' + i}
            uniqueID={'income-' + i}
            childID={i}
          />
        ))}
        <div className='btn-wrapper'>
          <button
            className='remove-btn'
            onClick={() => {
              if (newField !== 1) {
                setNewField(newField - 1);
              } else {
                return;
              }
            }}
          >
            -
          </button>
          <button
            className='addNewBTN'
            id='insert-above'
            onClick={() => {
              if (newField > 4) {
                return;
              } else {
                setNewField(newField + 1);
              }
            }}
          >
            +
          </button>
          <button className='done-btn' onClick={computeData}>
            NEXT
          </button>
        </div>
      </div>
    </Fragment>
  );
}
benjies
  • 1
  • 1
  • 2
    General advice, using DOM methods like `getElementById` is a [bad idea](https://stackoverflow.com/questions/66620392/how-bad-is-it-to-change-the-dom-in-react) in a React app. Also, don't use the console as a debug tool – Phil Oct 06 '21 at 22:52

0 Answers0