Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
How to push an object inside nested array using React and TypeScript?

What's the proper way, using TypeScript and React, to create a function that pushes a new object inside the array items ?

const [state, setState] = useState([
  {
    firstname: "William",
    items: [
      { name: "sword", damage: 100 },
      { name: "shield", damage: 50 },
    ],
  },
  {
    firstname: "Allison",
    items: [
      { name: "bow", damage: 70 },
      { name: "axe", damage: 120 },
    ],
  },
]);

const addNewItem = (newItem: object, CharacterIndex: number) => {

  // Push new item inside character's items.
  setState(newState)
};

return (
  <button onClick={() => addNewItem({ name: "dagger", damage: 50 }, 2)}>
    Add Item
  </button>
);

I have already done once using JavaScript, but with Typescript I often get some errors.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can Implement it the way you see it fits best.

const addNewItem = (newItem: object, CharacterIndex: number) => {

    //I would use this
    setState(state.map((elem: object, index: number) => {
        return index === characterIndex 
            ? { ...elem, items: [ ...elem.items, newItem ] }
            : elem;
    }));
};
about 4 years ago · Juan Pablo Isaza Report

0

You should type your state and all your arrays

import { useState } from "react";
import "./styles.css";

const INITIAL_STATE = [
  {
    firstname: "William",
    items: [
      { name: "sword", damage: 100 },
      { name: "shield", damage: 50 }
    ]
  },
  {
    firstname: "Allison",
    items: [
      { name: "bow", damage: 70 },
      { name: "axe", damage: 120 }
    ]
  }
];

type Item = {
  name: string;
  damage: number;
};

type StateParams = {
  firstname: string;
  items: Item[];
};

export default function App() {
  const [state, setState] = useState<StateParams[]>(INITIAL_STATE);

  const addNewItem = (newItem: Item, characterIndex: number) => {
    const nextState = state.map((st, i) => {
      if (i === characterIndex) {
        return {
          firstname: st.firstname,
          items: [...st.items, newItem]
        };
      } else {
        return st;
      }
    });

    setState(nextState);

    console.log(state);
  };

  return (
    <button onClick={() => addNewItem({ name: "dagger", damage: 50 }, 1)}>
      Add Item
    </button>
  );
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!