Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
React - How to use the current state value as a variable so i can set as a index inside an array

I am pretty a new to React and currently to use the current state of and object as a variable in another array, said array will start filled with 0, and every time someone press the vote button it will store +1 to said array index. I am sure its the wrong way but nevertheless I amtrying to figure out if is possible to use the logic i created.

Thanks for the patience!

import React, { useState } from 'react'

const App = () => {
  const anecdotes = [
    'If it hurts, do it more often',
    'Adding manpower to a late software project makes it later!',
    'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
    'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
    'Premature optimization is the root of all evil.',
    'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
    'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients'
  ]
   
  const [selected, setSelected] = useState(0)

  var ary = new Uint8Array(10); 
  //console.log('this', this.state);

  //show 1 anecdote
  //when user press next its generates a random number beetween 0 and 6 to display the anecdote
  //issue:
  //how to add said random value to my arrays so I can use the array to store the votes of each anecdote
  return (
    <div>
      <h1>{anecdotes[selected]}</h1>
      <button onClick={ () => setSelected(Math.floor(Math.random() * 6) ) }>Next Anecdote</button>
      
      <button onClick={ () => ary[selected.state] + 1  }>Vote</button>
      <p>votes: {ary[selected.state]}</p>
    </div>
  )
}

export default App
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

First, you'll need an array to hold the vote count values, and secondly, correctly update each vote count in an immutable update.

export default function App() {
  const [selected, setSelected] = useState(0);

  // create vote counts array from anecdotes array and initialize to zeros
  const [votes, setVotes] = useState(Array.from(anecdotes).fill(0));

  return (
    <div>
      <h1>{anecdotes[selected]}</h1>
      <button
        onClick={() => setSelected(
          // use anecdote array length
          Math.floor(Math.random() * anecdotes.length))
        }
      >
        Next Anecdote
      </button>

      <button
        onClick={() =>
          setVotes((votes) =>
            // immutable update, map previous state to next
            votes.map((count, index) =>
              index === selected ? count + 1 : count
            )
          )
        }
      >
        Vote
      </button>
      <p>votes: {votes[selected]}</p> // display selected anecdote vote count
    </div>
  );
}

Edit react-how-to-use-the-current-state-value-as-a-variable-so-i-can-set-as-a-index

about 4 years ago · Juan Pablo Isaza Relatório

0

All values which you change in React should be reactive, you never should change a value directly, because it will not trigger re-rendering. You should use useState hook.

In your case to store the anecdotes votes you could create a new array with length 6 and fill it with initial votes count - 0. Then you should call the hook to update the counts.

 const [votes, setVotes] = useState(new Array(6).fill(0));

 return (
    <div>
      <h1>{anecdotes[selected]}</h1>
      <button onClick={ () => setSelected(Math.floor(Math.random() * 6) ) }>Next Anecdote</button>
      
      <button onClick={ () => { setVotes(prevVotes => {
       const upd = [...prevVotes];
       upd[selected] += 1;
       return upd; 
})}  }>Vote</button>
      <p>votes: {votes[selected]}</p>
    </div>
  )
about 4 years ago · Juan Pablo Isaza Relatório

0

I think, using useReducer will help you keep everything in one place:

import React, { useState, useReducer } from "react";

const initialState = [
  { text: "If it hurts, do it more often", votes: 0 },
  {
    text: "Adding manpower to a late software project makes it later!",
    votes: 0
  },
  {
    text:
      "The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
    votes: 0
  },
  {
    text:
      "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
    votes: 0
  },
  { text: "Premature optimization is the root of all evil.", votes: 0 },
  {
    text:
      "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
    votes: 0
  },
  {
    text:
      "Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients",
    votes: 0
  }
];

const reducer = (state, action) => {
  if (action.type === "VOTE_UP") {
    return state.map((item, index) => {
      if (index === action.index) {
        item.votes = item.votes + 1;
      }
      return item;
    });
  }
};

const App = () => {
  const [anecdotes, dispatch] = useReducer(reducer, initialState);
  const [selectedIndex, setSelectedIndex] = useState(0);

  return (
    <div>
      <h1>{anecdotes[selectedIndex].text}</h1>
      <button
        onClick={() => {
          setSelectedIndex(Math.floor(Math.random() * 6));
        }}
      >
        Next Anecdote
      </button>

      <button
        onClick={() => {
          dispatch({ type: "VOTE_UP", index: selectedIndex });
        }}
      >
        Vote
      </button>
      <p>votes: {anecdotes[selectedIndex].votes}</p>
    </div>
  );
};

export default App;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda