If ternary in jsx is not working

Asked

Viewed 74 times

-1

I’m new to React and I’m trying to implement a route control, so I created an Auth file:

const Auth = {
    isAdmin: false,
    authenticate(){
        this.isAdmin = true
    },
    signout(){
        this.isAdmin = false
    },
    getAuth(){
        return this.isAdmin;
    }
}
export default Auth

When I log in and logout everything happens accordingly, in the login isAdmin becomes true and in the logout becomes false. But in the if ternary to show the logout option does not work, it is as if it did not make the comparison. But when printing the isAdmin value, the correct value appears:

{Auth.getAuth() ?( <li className="nav-item active">
              <a href="#" onClick={logout} style={{ textDecoration: "none" }}>
                <p className="nav-link">Log Out</p>
              </a>
            </li>) : null}

but even with isAdmin being true, this li is not rendered, and so is protected route control, I can never access it even though isAdmin is true:


function App() {
  return (
    <div>
      <div className="App">
        <Header />
        <Switch>
          <Route exact path="/" component={PostInfo} />
          <Route path="/register" component={Register} />
          <Route path="/login" component={Login} />
          <Route path="/post/:slug" component={Post} />
          <PrivateRoute path="/add" component={Add} />
        </Switch>
      </div>
    </div>
  );
}
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      Auth.getAuth() ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/",
          }}
        />
      )
    }
  />
);

I can’t find a problem with the code... and I’ve done a lot of research but everything seems to be right

  • Nobody knows how to help or point a direction

1 answer

0


The problem is that the state is not global, and therefore its Auth.getAuth() will always return false, that is, as you import this code into the component it will get its initial state, there is a way to maintain a state global where the components can share that same state that is with Context or Redux, I will propose the first with Context which is easier to reflect in your code:

///// Parte importante do Estado Global
const CounterContext = React.createContext();
const CounterProvider = ({children}) => {
  const [isLogado, setIsLogado]= React.useState(false);
  return (
    <CounterContext.Provider value={{isLogado, setIsLogado}}>
    {children}
    </CounterContext.Provider>
  )
}
///////////////////////////////////////
//Os componentes abaixo compartilham o mesmo Contexto
function App() {
  const {isLogado,setIsLogado} = React.useContext(CounterContext); 
  return (
    <div>      
      <button 
        onClick={e => setIsLogado(state => !state)}>
        {isLogado?"Sair":"Entrar"}
      </button>
    </div>
  )
}
function Menu() {
  const {isLogado,setIsLogado} = React.useContext(CounterContext);
  return (
    <div>
    {isLogado ? (<div>Logado</div>) : (<div>Não Logado</div>) }   
    </div>
  )
}
function Global() {
  return (
    <CounterProvider>
     <App/>
     <Menu/>
    </CounterProvider>
  )
}
//Renderiza o Global que disponibiliza o estado em todos os
//outros componentes
ReactDOM.render(<Global/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

In that code snippet:

function Global() {
  return (
    <CounterProvider>
     <App/>
     <Menu/>
    </CounterProvider>
  )
}

means that everyone will share the same state of the variable isLogado and any change will then be reflected in all components. The construction is very simple and the only way (of course Redux also does this) to share global state between components.

In your code your provider has to be the first component involving the others.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.