skip to Main Content

I’m trying to update the person which i get the data from people [array] let [person, setPeople] = useState(people);

why if I make this setPeople(person[0]) not work

I just a beginner in react and i know that’s a stupid question but i’m trying to explore

I tried to undertstand why it just take the whole person not an index but i can’t

2

Answers


  1. You have to decide if your state should contains one person or all people.
    In your code You mixed it.
    e.g. that would be okey:

     const[person, setPerson] = useState(people[0]);
     setPerson(person[0])
    

    Also in 99.9% of times You should use const for state instead of let.

    Login or Signup to reply.
  2. It would be great, if we had a minimal-reproducible-example

    Please find below a simple useState example, hope this helps. 🙂

    import { useState } from 'react';
    
    export default function Counter() {
      const [count, setCount] = useState(0);
    
      function handleClick() {
        setCount(count + 1);
      }
    
      return (
        <button onClick={handleClick}>
          You pressed me {count} times
        </button>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search