Home > database >  How is my reduce function getting an error after successfully iterating over the array?
How is my reduce function getting an error after successfully iterating over the array?

Time:08-21

I'm looking through a CSV file with name/stock symbol objects. When the user inputs a company name and clicks submit I'm searching through the file to locate the company record and extract the symbol.

Within a handleSubmit React function I've got a reduce that keeps failing the try/catch and throwing an error.

Data array looks like this:

[{"Symbol": "A", "Name": "Agilent Technologies Inc. Common Stock"}, {"Symbol": "AA", "Name": "Alcoa Corporation Common Stock"},etc.]

My functional component:

export function ParseAndSearch() {
 const [newAnswer, setNewAnswer] = useState({});

 // parse csv file here - output is 'data' array like above

 const handleSubmit => {
  // user input = userCompany (a string)

  try {
   let output = [];
   let tempAnswer = 
    data.reduce((output, company) => {
     if (company.Name.toLowerCase().includes(userCompany.toLowerCase())) {
      output.push(company);
     };
     let dummyAnswer = [...output];
     console.log('filtered list is: '   JSON.stringify(dummyAnswer));
     return output;
     }, []);

   setNewAnswer(tempAnswer);

  } catch (err) {
   console.log('error block');
  }
 }
 return (
  <div>
   Company Name: {newAnswer['Symbol']}
  </div>
}

The

How is my reduce failing? I'm getting results on "dummyAnswer" with each iteration but then it seems to fail when I get to the end of the reduce or when I try to "setNewAnswer."

I've had success with find (instead of reduce), but that does not help me as I need to return more than one answer for some searches.

CodePudding user response:

If you need to return more than one answer then you'll probably need to change the newAnswer state to an array and use the filter function:

const [newAnswer, setNewAnswer] = useState([]);

// parse csv file here - output is 'data' array like above

const handleSubmit = () => {
  // user input = userCompany (a string)

  const tempAnswer = data.filter((company) =>
    company.Name.toLowerCase().includes(userCompany.toLowerCase())
  );
  setNewAnswer(tempAnswer);
};

return (
    <div>
    {/* Display multiple answers */}
    {newAnswer.map((answer, index) => {
        return <div key={index}>Company Name: {answer.Symbol}</div>;
    })}
    </div>
)
  • Related