1

I have an dynamic created fields (input tag)

const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data

{navtive?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />
...
{rolls?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />

Expected Output:

const output = {
    native: [{id: 1, fee: "12"}, {id: 5, fee: "2"}],
    rolls: [{id: 4, fee: "1332"}],
};

onChange function :

const handleChange = (field, value, index) => {
    setData((prevState) => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    });
};

How to get the expected output ? What am I making wrong in the onChange function.

Thank you

9
  • The expected output doesn't make sense, since the maps are returning react components, not plain objects. Commented Dec 7, 2021 at 10:52
  • this is the expected output from onChange - [{id: 1, fee: "12"}, {id: 5, fee: "2"}] Commented Dec 7, 2021 at 10:54
  • Ah I see. May you also share the current output? Commented Dec 7, 2021 at 10:55
  • prevState is not iterable Commented Dec 7, 2021 at 10:56
  • 1
    @evolutionxbox That's not the problem. The problem is OP wants to spread it into an array and that will throw a TypeError. Commented Dec 7, 2021 at 11:02

1 Answer 1

2

You must add more arguments to handleChange for this output. type - to understand what property is native or rolls. id - id from current data element. Example - sandbox

const handleChange = (type, field, value, index, id) => {
    setData((prevState) => {
      const nextState = [...prevState[type]];
      nextState[index] = {
        ...prevState[type][index],
        id,
        [field]: value
      };
      return {
        ...prevState,
        [type]: nextState
      };
    });
  };

JSX

handleChange("native", "free", e.target.value, index, item.id)
Sign up to request clarification or add additional context in comments.

3 Comments

TypeError: prevState[type] is not iterable ` const [data, setData] = useState([ { native: [{}], rolls: [{}] }, ]);`
You have mistake , correct useState({ native: [{}], rolls: [{}] }) instead of const [data, setData] = useState([ { native: [{}], rolls: [{}] }, ]);
data is object not array, see above your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.