Search code examples
javascriptreactjsreturn

React conditional rendering not recognising true from state


So I have this simple function with conditional return:

export default function App() {
const appState = useState({
signed: true,
user: {
  login: null,
  password: null,
  rights: null,
},
});

return <div className="app">{appState.signed ? "does not" : "work"}</div>;
}

The problem is that the code always returns "work". Is it not possible to use conditional rendering with state?


Solution

  • useState hook returns an array of length 2.

     const [appState, changeAppState ] = useState({
    signed: true,
    user: {
      login: null,
      password: null,
      rights: null,
    },
    });
    
    ...
    
    //To change signed to true, try using the callback pattern
    
        changeAppState ((prevAppState) => ({
           ...prevAppState,
          signed: false
        }));
        
    //You can do this, but callback approach is safer
    
        changeAppState ({
           ...prevAppState,
           signed: false
        });