yoni
yoni

Reputation: 27

update boolean value in useState array

I have an useState with array in it, one of the value in the array is boolean. Im tring to update the value of the boolean by click.

so this is the button function:

    let Completed = () =>
      {
        let myPostFID = myPostFilterByUserId1.filter(x => x.id ==props.myID)
        
        setmyPostFID1(myPostFID)

    //so now this is the data i have in my state:
 
             

   userId:1
                id:1
                title:"delectus aut autem"
                completed:false

   // and this is how im tring to update the completed value:
     

        setmyPostFID1({...myPostFID,completed : "true"})
        
        
        
      }

Upvotes: 1

Views: 1636

Answers (2)

Igor Gonak
Igor Gonak

Reputation: 2250

const initialState = {
  userId: 1,
  id: 1,
  title: "delectus aut autem",
  completed: false
};

export default function App() {
  const [data, setData] = React.useState(initialState);
  const handleChange = (event) =>
    setData((prev) => {
      return {
        ...prev,
        completed: event.target.checked
      };
    });
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <input type="checkbox" value={data.completed} onChange={handleChange} />
      <p>State looks currently like following:</p>
      <p>{JSON.stringify(data)}</p>
    </div>
  );
}

https://codesandbox.io/s/cocky-neumann-tczrp5

Upvotes: 1

gavin
gavin

Reputation: 1354

this is what i found to work

const updatePostCompletion = index => {
  let newArr = [...myPostFID]; // copying the old posts array
  newArr[index].completed = true; // replace false bool with true

  setmyPostFID1(newArr);
}

this is a function that will create a new array with the old array data then will take the selected index in the state and change the completed bool to true.

after all that it will set the state to the new array that was just initialized

Upvotes: 1

Related Questions