NewbieAeg
NewbieAeg

Reputation: 637

Item not being removed from an array

I'm having an issue with my code where I cannot remove specific item from my array.

import React, { useState } from "react";
import Outcomeitem from "./Outcomeitem";
import { v4 as uuidv4 } from "uuid";

const Outcome = (props) => {
  const [input, setInput] = useState(0);
  const [expense, setExpense] = useState("");
  const [outcomes, setOutcomes] = useState([]);

  const setInputHandler = (e) => {
    e.preventDefault();
    props.onChangeHandlerOutcome(input);

    setOutcomes([
      ...outcomes,
      {
        name: expense,
        amount: input,
        id: uuidv4(),
      },
    ]);
  };

  const deleteOutcome = (id) => {
    setOutcomes(outcomes.filter((outcome) => outcome.id !== id));
  };

  return (
    <div>
      <form onSubmit={setInputHandler}>
        <label>
          Outcome
          <input
            type="text"
            name="name"
            onChange={(e) => setExpense(e.target.value)}
          ></input>
          <input
            type="text"
            name="name"
            onChange={(e) => setInput(parseInt(e.target.value))}
          ></input>
        </label>
        <input type="submit" value="Submit"></input>
      </form>
      <div>
        <div>
          {outcomes.map((outcome) => (
            <Outcomeitem
              name={outcome.name}
              amount={outcome.amount}
              deleteOutcome={(id) => deleteOutcome(id)}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

export default Outcome;
import React from "react";

const Outcomeitem = ({ name, amount, deleteOutcome, id }) => {
  return (
    <div>
      <div>
        <li>
          {name} : -{amount}${" "}
          <button onClick={() => deleteOutcome(id)}>Delete</button>
        </li>
      </div>
    </div>
  );
};

export default Outcomeitem;

I do have a feeling that it has something to do with me using a useState on the input and the amount - but i'm not entirely sure.

I'm not receiving any kind of error (apart from the unique key props one), it simply does nothing.

would appreciate any kind of help, thanks in advance!

Upvotes: 0

Views: 50

Answers (2)

NewbieAeg
NewbieAeg

Reputation: 637

I've figured out why it wouldn't work

at Outcome I've forgot to pass the ID prop in :

            <Outcomeitem
              name={outcome.name}
              amount={outcome.amount}
              deleteOutcome={(id) => deleteOutcome(id)}
            />

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

You never pass id as props here

<Outcomeitem
    name={outcome.name}
    amount={outcome.amount}
    deleteOutcome={(id) => deleteOutcome(id)}
 />

Alternatively you can just pass deleteOutcome={() => deleteOutcome(outcome.id)} as props and then directly invoke deleteOutcome from Outcomeitem.

Upvotes: 1

Related Questions