Search code examples
javascriptreactjsreact-hooksconditional-statementsuse-state

How to use state variable for conditional declaring of array of objects?


In React js, What I want to do is: declare an array of objects (routes) and export. For conditional declaration of array of objects, I want to use an state variable (which returns whether user logged in or not).

Aim:

  • user logged in, show Put Rating option
  • user not logged in, dont show Put Rating option.

The file of array of objects which I have to export for mapping

import {AppState} from '../AppContext';

function IsLoggedIn(){
   const {user} = AppState();
   return user===null;
}

const routes=[
  {
    title:"home page",
    show:true,
  },
  {
    title:"put rating",
    show: IsLoggedIn(),
  }
];

export default routes;

It returns error like hooks can only be used inside body of functions.


Solution

  • Move your AppState to a context/reducer so that whenever a user authenticates we can properly react to this state change then

    const routes=[
      {
        title:"home page",
        private:false,
      },
      {
        title:"put rating",
        private:true,
      }
    ];
    

    Create a separate component called PrivateWrapper or anything you like and inside that put this logic

    export default function PrivateWrapper(props){
        const {user} = AppState();
        return !user ? null : props.children;
    }
    

    Finally when looping through the routes array just check if private is true then wrap the element with PrivateWrapper

    routes.map(route =>(
    route.private ? 
    <PrivateWrapper>{route.title}</PrivateWrapper> : route.title
    ))
    

    You can also use this wrapper with any element you want.