suvop
suvop

Reputation: 51

Push array of an object to array

    const [ post, setPost] = useState([])

    function addMemo() {
        let memo = [
                { id:1, name:'shyam', post:'developer' },
                { id:2, name:'ram', post:'porter' },
                { id:3, name:'prakash', post:'cobler' },
                { id:4, name:'sanj', post:'designer' },
                { id:5, name:'anil', post:'pilot' },
                { id:6, name:'gopal', post:'laptain' }
            ]
        
        setPost( [...post, memo] )
     }

    return (
         <button type="button" onClick={() => addMemo()}>Click Me</button>
   )

here is my code but I could not push array of object to the existing array Push array of an object to existing array,

Upvotes: 1

Views: 52

Answers (2)

Kondalarao V
Kondalarao V

Reputation: 800

Whenever you are updating state based on previous state it is better to pass a function to the setState function.

setPost((prevPost) => [...prevPost, memo] )

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

Use ... spread operator for the memo.

    setPost( [...post, ...memo] )

Upvotes: 2

Related Questions