1
    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,

2
  • @william's anser is correct but just fyi you should reference your addMemo and not rebind it on every call like onClick={addMemo} Commented Apr 27, 2021 at 4:20
  • I also met this kind of problem. I tried the below method but now working. Commented Apr 27, 2021 at 4:46

2 Answers 2

2

Use ... spread operator for the memo.

    setPost( [...post, ...memo] )
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

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.