Reputation: 115
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?
Upvotes: 1
Views: 160
Reputation: 20431
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
});
Upvotes: 1
Reputation: 4332
The useState
hook gives you an array with the state value and a setter method.
The problem is that you're accessing that array returned by useState
and you can't access signed
it results in a false
which makes the text 'work' to be displayed
So do this instead
export default function App() {
const [appState, setAppState] = useState({
signed: true,
user: {
login: null,
password: null,
rights: null,
},
});
return <div className="app">{appState.signed ? "does not" : "work"}</div>;
}
Upvotes: 2