Home > OS >  React - How to use the current state value as a variable so i can set as a index inside an array
React - How to use the current state value as a variable so i can set as a index inside an array

Time:11-04

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

CodePudding user response:

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

CodePudding user response:

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>
  )

CodePudding user response:

The useState doest return an object, in this case will return a number, because the default value you are passing in is 0. You can use another useState to track the value of the votes for each anecdote, even if you change of anecdote the score will stay.

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 anecdotesObjects = anecdotes.map(anecdote => ({ score: 0, anecdote }))

    const [selected, setSelected] = useState(0)
    const [scoredAnecdotes, setScoredAnecdotes] = useState(anecdotesObjects)

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

            <button onClick={() => {
                setScoredAnecdotes(() => {
                    const aux = [...scoredAnecdotes]
                    aux[selected].score  ;
                    return aux
                })
            }
            }>Vote</button>
            <p>votes: {scoredAnecdotes[selected].score}</p>
        </div>
    )
}

export default App

CodePudding user response:

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;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related