skip to Main Content

I initialized a new constant like that :

    const [data, setData] = useState([
     {
      id: "a1",
      score: "",
      name: "MyA1"
     },
     {
      id: "a2",
      score: "",
      name: "MyA2"
     }
    ]);

I want to change the score with setData. But I don’t know how to access to data[0].score and data[1].score with setData

I tried to do :

    const updateList = (data) => {
      setData(previousState => {
        return { ...previousState, score:'Good' }
      });
    }

but it is not working because with this code I can’t access to data[0]. I tried also :

   const updateList = (data) => {
      setData(previousState => {
        return { ...previousState, previousStat[0].score:'Good' }
      });
    }

but it is not working too.

Do you know how to do that ? Thank you !!

2

Answers


  1. You can do this by retrieve the current state of data using setState.
    Try this.

    const updateList = () => {
      setData(previousState => {
        const updatedData = previousState.map(item => {
          if (item.id === "a1") {
            return { ...item, score: "Good" };
          }
          return item;
        });
        return updatedData;
      });
    };
    
    Login or Signup to reply.
  2. Your first issue is that your useState hook is managing an array of objects. The first code snippet you provided is trying to spread the array like it’s an object, which isn’t quite right. The second snippet contains a syntax error (you’re trying to use object property assignment inside the spread operator).
    try this :

    const updateList = () => {
    setData(previousState => [
    { ...previousState[0], score: 'Good' },
      ...previousState.slice(1)
    ]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search