Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a filtered array based on user input javascript

I have an user input.

Based on that input I need to filter an array of options.

I have been able to submit the data, I am now inside my handleSubmitData function where I am writing the if conditions which should then return a filtered array of results to the screen however this is not happening. It must be to do with scope however I cannot seem to figure out what is wrong. Here is the code. Any guidance would be helpful

const Container = () => {
  const [cards, setCards] = useState([
    "studentCard",
    "anywhereCard",
    "liquidCard",
  ]);
  

  const handleSubmitData = (userInput) => {
    const { employmentStatus } = userInput.state;
    const { earnings } = userInput.state;

    if (employmentStatus === "student" && earnings < 16000) {
      return cards.filter((card) => card !== "liquidCard");
    }
    if (employmentStatus === "student" && earnings >= 16000) {
      return cards;
    }
    return cards;
  };

  return (
    <div className="Container">
      <UserInputForm submitData={handleSubmitData} />
        {cards} 
    </div>
  );
};

export default Container;

I have put cards within my render return part of the component but nothing happens there are no filtered cards..

like image 366
Angela Inniss Avatar asked Apr 22 '26 01:04

Angela Inniss


1 Answers

Set filtered cards to cards state on handleSubimitData.

const Container = () => {
  const allCards = ['studentCard', 'anywhereCard', 'liquidCard'];
  const [cards, setCards] = useState([]);

  const handleSubmitData = userInput => {
    const { employmentStatus } = userInput.state;
    const { earnings } = userInput.state;

    let filtered = [...allCards];

    if (employmentStatus === 'student' && earnings < 16000) {
      filtered = allCards.filter(card => card !== 'liquidCard');
    }

    setCards(filtered);
  };

  return (
    <div className="Container">
      <UserInputForm submitData={handleSubmitData} />
      {cards}
    </div>
  );
};

export default Container;
like image 187
baymax Avatar answered Apr 24 '26 13:04

baymax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!