1

I'm trying to increase the value of an array of an specific position. Let's say you have an array:

const [cantidad, setCantidad] = useState([
   {cantidadID: 1, value: 1},
   {cantidadID: 2, value: 1},
   {cantidadID: 3, value: 1}
]);

Now I would like to change the value of ONLY one of those (doesn't matter which one) with a button

const plus = (e) => {
   setCantidad(cantidad[e] + 1);
};

const minus = (e) => {
   if (cantidad[e] > 0){
      setCantidad(cantidad[e] - 1);

   } else {
      window.alert("Sorry, Zero limit reached");
      setCantidad(0);
   }
};

e being the index of the array (with some smart coding ofc) being send from a table pretty much like this

{libros.map((l) => (                   
   <tr>
      <td>
         <button onClick={mas} />
         {cantidad}
         <button onClick={menos} />
      </td>

      <td>{l.grado}</td>

      <td>
         <input
            onChange={(event) => {
               let checked = event.target.checked;
            }} 
            type="checkbox"
            checked=""
         >
         </input>
         {l.descripcion}
      </td>

      <td>{l.editorial}</td>
      <td>${parseFloat(l.precio).toFixed(2) * cantidad}</td>
   </tr>
))}

// I know the checkbox is not working. I'm still working through that.

Now in my head it does make sense that while is mapping there should be a variable controlling the Index of the cantidad variable but if I try to make a new variable inside the map it goes crazy and it crashes, (Unless i'm formating it wrong or putting it in the wrong place)

So I got the logic is very simple but I do not know how to apply it it would be something like: If you have X[] Variable while mapping make a Y variable that controls the ID of the array variable and if you want to change the value of an specific value from X[] then you must send the X[Y] variable to the button const plus and minus and then only change that variable from that specific ID.

In my full code I'm not using 3 values btw the values are equal to the amount of data that is bringing from the map

Any tips, data or information is appreciate it. If you require the actual input with my whole code let me know as well if I do not get it working I'll probably post the code later.

This is the actual code I'm working on and even though the first question got answered I'm still having issues with the next part (Only relevant part)

const [amount, setAmount] = useState([1]);

//I know this bit doesn't make sense (Yet) I'm trying to figure out first the first bit
const plus = (index) => {
        setAmount(amount[index] + 1);
      };

      const menos = (index) => {
        if (amount[index] > 0){
            setAmount(amount[index] - 1);
        }
        else {
            window.alert("Sorry, Zero limit reached");
            setAmount(0);
        }
      };

{books.map((l, index) => (
                        
                        <tr >
                        
                        <td>
                            <button onClick = {() => plus(index)}/>
                            {amount[index]}
                            <button onClick = {() => minus(index)}/>
                        </td>
                        <td>{l.grado}</td>

                        <td >
                        <input onChange = {(event) => {
                            let checked = event.target.checked;
                        }} 
                        
                        type="checkbox" checked = "">
                        </input>
                        {l.descripcion}
                        </td>

                        <td >{l.editorial}</td>
                        <td >${parseFloat(l.precio).toFixed(2) * amount[index]}</td>
                        </tr>

                     ))}

and this is how is printing enter image description here

I know in Javascript you can use Array(5).fill(2) is there something similar to that? like I would like to do Array(map.length).fill(1) for example so the value always starts with 1 and then all I have to do is to play with the index to change the correct one with plus and minus.

ReactPotato
  • 1,262
  • 3
  • 26
  • 46

2 Answers2

2

It is the second argument of .map function so:

libros.map((l, idx)

where idx is your i

Here is documentation about it

isherwood
  • 58,414
  • 16
  • 114
  • 157
Sowam
  • 1,674
  • 3
  • 12
  • 30
  • Oh, well I feel like a clown now. Quick question how do I send the ID through the buttons though because yes I have the id now but how I send it to the button so it changes only that id `````` didn't work I though I would send the id as an argument for the ```const plus``` function – ReactPotato Sep 17 '21 at 19:43
  • 1
    @ReactPotato it should be `onClick = {() => plus(id)}` so on click you are executing plus function with id as an argument – Sowam Sep 17 '21 at 19:45
  • 2
    @ReactPotato just to make things clear, it's an *index* not an *id*. – Arkellys Sep 17 '21 at 19:45
  • right Index yeah cause is the position not the ID, is there a way to make that all the values start with 1 ? because if I state that in the beginning only the first one starts with 1 if I for example do this: ```{cantidad[1, index]}``` all of them stay in blank – ReactPotato Sep 17 '21 at 19:49
  • 2
    @ReactPotato I think you should take the time to read the documentation on [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – Arkellys Sep 17 '21 at 20:00
  • Saw the documentation and I get a better idea now of how to call things but didn't find a similar example with my particular situation and didn't find a way to make the same value for all the index. – ReactPotato Sep 17 '21 at 20:43
  • @ReactPotato if you have another problem please post another question and do not edit this one. – Arkellys Sep 18 '21 at 10:47
  • Yeah sorry I realize that and did another one [link](https://stackoverflow.com/questions/69229987/how-to-fill-an-array-with-the-same-values-x-times-and-how-to-send-the-data-corre/69230356#69230356) – ReactPotato Sep 18 '21 at 14:23
1

You are setting an object in an array based on the index value, and not an actual id. Recommend heavily that you incorporate an id into each object, then grab the object by id to manipulate it. Otherwise you could experience bugs and unexpected behaviors as you manipulate the array.

Same concept as not using the index of an array when using map: this is an anti-pattern.

https://reactjs.org/docs/lists-and-keys.html

TR3
  • 327
  • 3
  • 6
  • well the array doesn't have any real value atm not even id's nothing, my idea was to just give 1 to everything cause the quantity will ALWAYS start on 1 and then change it individually by doing a plus/minus function (which I'm pretty sure that by reading that doesn't seem like a good practice) – ReactPotato Sep 17 '21 at 19:46