Utilizing styled components for retrieving JSON data with an alternate key identifier

import styled from "vue-styled-components";
const props = { type: String, action: Boolean };

const getter = () => {
  const permissionsList = JSON.parse(localStorage.getItem("UZ")).permissions;
  const type = props.type;
  const action = props.action;

  return permissionsList.type.action;
};

export const stylePermission = styled("span")`
  pointer-events: ${getter() ? "" : "none"};
  cursor: ${getter() ? "pointer" : "not-allowed"};
  opacity: ${getter() ? 1 : 0.4};
`;

This code snippet is being utilized in the following manner:

<template slot="tab-head-roles">
   <sp-permission type="user" action="can_approve">
      <router-link to="/settings/roles">Roles</router-link>
   </sp-permission>
</template>

An issue arises when trying to access

return permissionsList.type.action;
because the keys type and action do not directly exist in the JSON Object, even though their values are present within the object.

How can I best approach accessing this information?

Answer №1

To access specific values based on the keys of type and action, you can utilize square brackets in this manner:

const fetchPermissions = () => {
  const userPermissions = JSON.parse(localStorage.getItem("UZ")).permissions;
  const type = props.type;
  const action = props.action;

  return userPermissions[type][action];
};

Answer №2

Here is my solution to the problem:


import styled from "vue-styled-components";
const permissionProps = { type: String, action: String };

const computedPermissions = JSON.parse(localStorage.getItem("UZ")).permissions;

export const stylePermission = styled("span", permissionProps)`
  pointer-events: ${props => (computedPermissions[props.type][props.action] ? "" : "none")};
  cursor: ${props =>
    computedPermissions[props.type][props.action] ? "pointer" : "not-allowed"};
  opacity: ${props => (computedPermissions[props.type][props.action] ? 1 : 0.4)};
`;


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display loader while waiting for file to be loaded

I am utilizing ajax to retrieve a file. The loading animation is functioning properly with the ajax request, however, the file size is notably large. I am interested in implementing a preloader that will display until the file has finished loading. ...

provide the key and id to a node.js module

Currently, I am utilizing the Express framework to establish a module for handling requests to a third-party API. This particular API necessitates an ID and key to be transmitted. Rather than embedding these credentials directly into the module, I prefer ...

Is there a method to prompt Angular to alert me when utilizing an undeclared directive in a template?

At times, I find myself making typos in the angular directive's name or the element tag within its template. However, the only indication I receive is the directive mysteriously disappearing. It would be helpful if angularjs could alert me when I at ...

Getting data from an API with authorization in Next.js using axios - a step-by-step guide

click here to view the image user = Cookies.get("user") I'm having trouble accessing this pathway. I stored user data, including the token, using cookies. Please assist me with this issue. ...

Unleashing the Power of Google Apps Script Filters

Having some data in a Google Sheet, I am looking to filter it based on specific criteria and return corresponding values from another column. Additionally, I need to count the number of elements in the resulting column. Below is an example of the data: Sa ...

Validating Users with OpenID in Vue.js

Utilizing the oidc-client in a basic VueJs project. The IDP server information is correctly configured in SecurityServices.js, with the following oidc config: var mgr = new Oidc.UserManager({ userStore: new Oidc.WebStorageStateStore(undefined), aut ...

What could be the reason for the list being undefined even though I explicitly defined it within the <script setup> section of my Nuxt 3 Project?

I am currently working on a Nuxt 3 Project and have created a component that generates a variable amount of elements. When calling the element, it is passed an array as a parameter. In the script setup, I define this array as 'list' and intend to ...

The functionality of iOS 9 is hindering the accessibility of modal mobile links

On my website, I am using modal to display necessary information that requires users to click on buttons such as back and submit. However, the links seem broken even though they are supposed to redirect to another page. Whenever a button is clicked, the pa ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

Utilizing the protractor tool to navigate through menu options and access submenus efficiently

I am new to using Protractor and I'm struggling to write code that can select the menu, submenus, and click them within the div with id="navbar". Can someone please assist me with this issue? Unfortunately, I am facing difficulties posting the HTML co ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Minimize Vue Bundle Size for Optimal Vue Performance

Currently facing a major performance issue with Vue during the initial load due to the size of the vue-plotly package. Interestingly, I am not directly using the vue-plotly package, but my Vue-pivottable (Pivot Table Component) is utilizing it. I have att ...

Express functions properly when handling the root route, but encounters issues with sub routes as it sends empty response bodies

Inside the routes.ts file: const router:Router = express.Router() // Route to get all blogs router.get('/',async (req:Request,res:Response)=>{ res.status(200).send("message sent") }) router.get('/admin',async (req:Requ ...

Vue 3 gracefully handles errors by displaying an alternative component

I am currently developing a rendering library for my Vue 3 + Vite project. Essentially, I have a JSON array of products which I pass to a special <Render :products /> component. This Render component reads all the JSON products and converts them in ...

Creating an array of form input names using JavaScript within the HTML input tag

I have a two part question that I'm hoping someone can help me with. There was a similar question asked recently that included information about this particular type of array in PHP, but unfortunately, I can't seem to locate it at the moment. 1. ...

When location.href is used, the page freezes up

When attempting to transition to another page by clicking on a button, I encountered an issue where the intended page would hang. The transitions to other pages worked fine, but not the specific one I needed: location.href = http://localhost:3306/mountainB ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

How to Send an Ajax Request from a Vue.js Application to WordPress

I've designed a custom page template to seamlessly integrate a vue app into an existing website <?php /* * Template Name: Registration Form */ get_header(); ?> <div id="app"></div> <?php get_footer(); ?> After some ...

Ways to retrieve a specific value in an array of objects

When working with the p5 javascript library, there is a convenient built-in function called {key} that captures the key you press. For instance, using text(${key},200,200) will display the key pressed at position 200, 200 on the canvas. If I were to stor ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...