A
A
alesik2022-02-18 17:12:32
React
alesik, 2022-02-18 17:12:32

How to make a boolean property toggle in a state?

function Toggle() {
  let [state, setState] = useState({
    fromBook: [
      { text: "Отрывок из книги 1" },
      { text: "Отрывок из книги 2" },
      { text: "Отрывок из книги 3" },
    ],
    show: false,
    id: 0,
  });

  function showExcerpt() {
    let show = state.show;
    setState({ show: !show });
    console.log(state.show);
    console.log(state.fromBook);
{/*После второго нажатия state.fromBook становится undefined:*/}

  }

  return (
    <div>
      <button onClick={showExcerpt}>Показать отрывок </button>

      {/* <p>{state.excerpts[state.id].text}</p> */}
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel, 2022-02-18
@Asokr

setState({ show: !show });
This is how you rewrite state

0
0xD34F, 2022-02-18
@0xD34F

Split the state object - make a separate call to useState for each of its properties.
Or copy all properties on update: . setState({ ...state, show: !state.show });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question