Adding multiple IDS within an array?

Asked

Viewed 106 times

2

const [pergunta, setAddPergunta] = useState([])
async function pegarId(_id) {setAddPergunta(_id) 
    console.log(_id)}
 <tbody>
    {getPerg.map((pe, i) => (
        <tr key={i}>
            <th scope="row">{pe.area}</th>
            <td
                onClick={() => pegarId(pe._id)}
            >
            {pe.pergunta}<br></br>
                <strong>Responder: </strong> <label> Sim </label> <input
                    value={false}
                    onChange={e => setResposta(e.target.value)}
                    type="radio"
                /> <label> Não </label> <input
                    value={true}
                    onChange={e => setResposta(e.target.value)}
                    type="radio"
                />
            </td>
        </tr>
    ))}
</tbody>

What’s happening when I use the click to catch the ID of the question?

{
    "pergunta":["5d6fa2fad1af7d3070ea7e8e"],
    "_id":"5d71078671e10832c8e87e5d",
    "responsavel":"Pedro",
    "time":"5d6fe08e1814790dd084219a",
    "createdAt":"2019-09-05T13:03:02.445Z","updatedAt":"2019-09-05T13:03:02.445Z",
    "__v":0
}

What I wanted to happen was to save array of a question in the bank.

{
    "pergunta":'[
        "5d6fa2fad1af7d3070ea7e8e", 
        "5d6fa86bd1af7d3070ea7e8f", 
        "5d6fa881d1af7d3070ea7e90"
    ]',
    "_id":"5d71078671e10832c8e87e5d",
    "responsavel":"Pedro",
    "time":"5d6fe08e1814790dd084219a",
    "createdAt":"2019-09-05T13:03:02.445Z","updatedAt":"2019-09-05T13:03:02.445Z",
    "__v":0
}

Already use the method push to add another array and nothing like doing to catch the click the IDS and add inside the array?

  • 2

    Ola pedro, only a suggestion, is worth taking a look at this publication of [meta], because your question of the way it was written is falling into one of the items covered in it, and this can make you be negativated - Manual on how NOT to ask questions =D

1 answer

4


You can do it like this:

async function pegarId(_id) {
    setAddPergunta([...pergunta, _id]) 
}

These three dots are the spread operator it works for objects as well, what it is doing and extending the values that already exist within a new array and adding a new value to those that already exist and as if you do this

pergunta =  [...pergunta, _id]

And in the react the state is immutable it does not change so if you had managed to use the push you would be violating this immutability because you would be editing the current state, and in this way I showed you this creating a new state, in memory is another array, which is the correct way to work with state in the react.

  • Thanks, it worked out.

  • blz, I changed the responsta I put an explanation for really you understand and not only copy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.