Home > Mobile >  Push Object to Array UseState
Push Object to Array UseState

Time:11-18

I am learning ReactJs, and building a sample project. I am facing a problem while pushing the items to the array. My application has a list(10 items) and I am trying to push props to an array; But I am facing the below issues:

  1. On click of "Choose" button, first time item does not push into the array, but it pushes on the second click.
  2. When I click on the other li item the first item pushed to the array is deleted and the second item pushes to it.

I am trying to solve this for the last few hours, I tried other solutions on this platform but nothing works. What I am doing wrong.

 import React, {useState} from 'react';
    const MItem = (props)=>{
    
        const [nameList, setName] = useState([]);
       
        const NameHandler = ()=>{
              setName(nameList => [...nameList, props]);
        }
      return (
   <div>
        <div>
        <h3>{props.title}</h3>    
        <img src={props.pic} />
        <p>{props.year}</p>
        </div>
          <div>
           <button onClick={NameHandler}> Choose </button>
         </div>
        </div>
        
     )
    }
    export default MItem;

CodePudding user response:

Lets assume, you sent test using the attribute value as below

<MItem value="test">

Now you should use props.value not props

setName(nameList => [...nameList, props.value]);

Here is your example:

import React, {useState} from 'react';
const MItem = (props)=>{

    const [nameList, setName] = useState([]);
   
    const NameHandler = ()=>{
          setName(nameList => [...nameList, props.value]);
    }
  return (
    <button onClick={NameHandler}> Choose </button>
 )
}
export default MItem;

More detail

CodePudding user response:

you don't need to pass a function to setName you can just do. Based on your comments

const NameHandler = ()=>{
      const item = {title: props.title, pic: props.pic}

      setName([...nameList, item]);
}
  • Related