1

I have have no error in my code. But my condition, finally don't work.

  const togglePeronsHandler = () => {
    const doesShow = personsState.showPersons;
    personsState.showPersons = !doesShow;

    console.log(personsState);
  }

  (...)

  <button className="btn btn-sm btn-primary" 
    onClick={togglePeronsHandler}>Toggle Person
  </button>
  <div className="persons">
      {
       personsState.showPersons === true ?
     (
   personsState.persons.map( (item, index) => (
   <Person name={ item.name }
           index={index}
           age={ item.age }
           click={switchNameHandler}
           changed={nameChangeHandler}/>
  ))
 ) :
 (
   <div className="alert alert-info">No body</div>
 )
} 

When I click on button, personsState.showPersons passed true/false. But rendering it wasn't effect…

At origin, i have change setPersonState but it didn't do anything...


Sandbox : https://codesandbox.io/s/3yn05lro81

2 Answers 2

1

Since personsState is immutable, you can't re-assign it. You have to set it with setPersonsState like you did in the other functions.

I see you need the previous state in order to do that (that's probably where your confusion came from). Apart from the object syntax of setState({...newState}) there is another syntax that takes a callback function: setState(previousState => { return {...newState} }). This is solved using this callback setState syntax.

This way, your togglePersonsHandler function would look like this:

const togglePersonsHandler = () => {
  setPersonsState(previousPersonsState => {
    const doesShow = previousPersonsState.showPersons;
    return {
      ...previousPersonsState,
      showPersons: !doesShow
    };
  });
};

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it looks like Redux.
0

I thnk you need to call setPersonsState in your toggle function:

  const togglePeronsHandler = () => {
    const doesShow = personsState.showPersons;
    setPersonsState({showPersons:!doesShow, persons: personsState.persons});
  }

Without setPersonsState, your component will not rerender.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.