Code Monkey home page Code Monkey logo

powerbi-client-react's Introduction

powerbi-client-react

Power BI React component. This library enables you to embed Power BI reports, dashboards, dashboard tiles, report visuals, Q&A or paginated reports in your React application, and to create new Power BI reports directly in your application.

Quick Start

Import

import { PowerBIEmbed } from 'powerbi-client-react';

Embed a Power BI report

<PowerBIEmbed
	embedConfig = {{
		type: 'report',   // Supported types: report, dashboard, tile, visual, qna, paginated report and create
		id: '<Report Id>',
		embedUrl: '<Embed Url>',
		accessToken: '<Access Token>',
		tokenType: models.TokenType.Embed, // Use models.TokenType.Aad for SaaS embed
		settings: {
			panes: {
				filters: {
					expanded: false,
					visible: false
				}
			},
			background: models.BackgroundType.Transparent,
		}
	}}

	eventHandlers = {
		new Map([
			['loaded', function () {console.log('Report loaded');}],
			['rendered', function () {console.log('Report rendered');}],
			['error', function (event) {console.log(event.detail);}],
			['visualClicked', () => console.log('visual clicked')],
			['pageChanged', (event) => console.log(event)],
		])
	}

	cssClassName = { "reportClass" }

	getEmbeddedComponent = { (embeddedReport) => {
		this.report = embeddedReport as Report;
	}}
/>
<PowerBIEmbed
	embedConfig = {{
		type: 'report',   // Supported types: report, dashboard, tile, visual, qna and paginated report
		id: undefined,
		embedUrl: undefined,
		accessToken: undefined,    // Keep as empty string, null or undefined
		tokenType: models.TokenType.Embed
	}}
/>

Note: To embed the report after bootstrap, update the props (with at least accessToken).

Demo

This demo includes a React application that demonstrates the complete flow of embedding a sample report using the PowerBIEmbed component.

The demo shows how to bootstrap the report, embed it, and update it. Additionally, the demo showcases the usage of the powerbi report authoring library by enabling the user to change the type of visual from a report using the "Change visual type" button.

The demo also sets a "DataSelected" event, which allows the user to interact with the embedded report and retrieve information about the selected data.

To run the demo on localhost, run the following commands:

npm run demo

Redirect to http://localhost:8080/ to view in the browser.

Usage

Use case Details
Embed Power BI To embed your powerbi artifact, pass the component with atleast type, embedUrl and accessToken in embedConfig prop.
Get reference to the embedded object Pass a callback method which accepts the embedded object as parameter to the getEmbeddedComponent of props.
Refer to the getEmbeddedComponent prop in Quick Start.
Apply style class Pass the name(s) of style classes to be added to the embed container div to the cssClassName props.
Set event handlers Pass a map object of event name (string) and event handler (function) to the eventHandlers prop.
Key: Event name
Value: Event handler method to be triggered
Event handler method takes 2 optional params:
First parameter: Event
Second parameter: Reference to the embedded entity
Reset event handlers To reset event handler for an event, set the event handler's value as null in the eventHandlers map of props.
Set new accessToken To set new accessToken in the same embedded powerbi artifact, pass the updated accessToken in embedConfig of props.
Reload manually with report.reload() after providing new token if the current token in report has already expired
Example scenario: Current token has expired.
Update settings (Report type only) To update the report settings, update the embedConfig.settings property of props.
Refer to the embedConfig.settings prop in Quick Start.
Note: Update the settings only by updating embedConfig prop
Bootstrap Power BI To bootstrap your powerbi entity, pass the props to the component without accessToken in embedConfig.
Note: embedConfig of props should at least contain type of the powerbi entity being embedded.
Available types: "report", "dashboard", "tile", "visual", "qna" and "paginated report".
Refer to How to bootstrap a report section in Quick Start.
Using with PowerBI Report Authoring 1. Install powerbi-report-authoring as npm dependency.
2. Use the report authoring APIs using the embedded report's instance
Phased embedding (Report type only) Set phasedEmbedding prop's value as true
Refer to Phased embedding docs.
Apply Filters (Report type only) 1. To apply updated filters, update filters in embedConfig props.
2. To remove the applied filters, update the embedConfig prop with the filters removed or set as undefined/null.
Set Page (Report type only) To set a page when embedding a report or on an embedded report, provide pageName field in the embedConfig.
Create report To create a new report, pass the component with at least type, embedUrl and datasetId in embedConfig prop.

Note: To use this library in IE browser, use react-app-polyfill to add support for the incompatible features. Refer to the imports of demo/index.tsx.

Props interface

interface EmbedProps {

	// Configuration for embedding the PowerBI entity (required)
	embedConfig:
		| IReportEmbedConfiguration
		| IDashboardEmbedConfiguration
		| ITileEmbedConfiguration
		| IQnaEmbedConfiguration
		| IVisualEmbedConfiguration
		| IPaginatedReportLoadConfiguration
		| IReportCreateConfiguration

	// Callback method to get the embedded PowerBI entity object (optional)
	getEmbeddedComponent?: { (embeddedComponent: Embed): void }

	// Map of pair of event name and its handler method to be triggered on the event (optional)
	eventHandlers?: Map<string, EventHandler>

	// CSS class to be set on the embedding container (optional)
	cssClassName?: string

	// Phased embedding flag (optional)
	phasedEmbedding?: boolean;

	// Provide instance of PowerBI service (optional)
	service?: service.Service
}

Supported Events

Events supported by various Power BI entities:

Entity Event
Report "buttonClicked", "commandTriggered", "dataHyperlinkClicked", "dataSelected", "loaded", "pageChanged", "rendered", "saveAsTriggered", "saved", "selectionChanged", "visualClicked", "visualRendered"
Dashboard "loaded", "tileClicked"
Tile "tileLoaded", "tileClicked"
QnA "visualRendered"

Event Handler to be used with Map

type EventHandler = (event?: service.ICustomEvent<any>, embeddedEntity?: Embed) => void | null;

Using supported SDK methods for Power BI artifacts

Import

Import the 'PowerBIEmbed' inside your targeted component file:

import { PowerBIEmbed } from 'powerbi-client-react';

Use

You can use report state to call supported SDK APIs.

Steps:

  1. Create one state for storing the report object, for example, const [report, setReport] = useState<Report>();.

  2. Use the setReport method inside the component to set the report object.

<PowerBIEmbed
	embedConfig = { sampleReportConfig }
	eventHandlers = { eventHandlersMap }
	cssClassName = { reportClass }
	getEmbeddedComponent = { (embedObject: Embed) => {
		setReport(embedObject as Report);
	} }
/>
  1. Once the report object is set, it can be used to call SDK methods such as getVisuals, getBookmarks, etc.

async getReportPages(): Page[] {
	// this.report is a class variable, initialized in step 3
	const activePage: Page | undefined = await report.getActivePage();
	console.log(pages);
}

Dependencies

powerbi-client

Peer dependencies

react

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments

Data Collection.

The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications.

If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at Microsoft Privacy Statement. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

Support

Our public support page is available at Microsoft Support Statement.

powerbi-client-react's People

Contributors

ali-hamud avatar anant-k-singh avatar bapat-atharva avatar kenakamu avatar kkd1215 avatar kotanasai21 avatar mayur007b avatar microsoft-github-operations[bot] avatar microsoftopensource avatar mishra-prachi avatar orshemesh16 avatar rad10wave avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powerbi-client-react's Issues

Detect slicers changes in embedConfig

Thanks for this great component.

I noticed that the component reacts when the pageName in the embedConfig changes.

It would also be nice if the component could react when the slicers object in the embedConfig changes.

Any plan for Angular?

Hi! I want to use your library in my angular project. I was wondering if you have planned an Angular version.

Reload or Refresh automatically after detect an error

I've been working with PowerBI Embedded in some projects and I discovered that exists a common use case in this project. This is when the client stops the dedicated capacity at some hours to reduce costs and resume at another time.

I've noticed that an error is capture by this component or powerbi client, and displays a message to notify the user of what happened. But if the user keeps in the view without refreshing the page the error keeps displayed until the user hits the ok button and after that nothing is showing.

Is this a common scenario? do you consider that needs to be handled by this library?

Requirement for specific region settings

Hi just wondering if there is any method to force the Language/Region that will be used for the date pickers?

Right now the way the Power Bi viewer is using the browser to choose the date/region settings is causing an issue for me where my "English (Ireland)" (Windows 10 PC) is showing an "English (United States)" (Somehow chosen by MS Edge...) format? The way I'm dealing with locale and i18n for the rest of the app is by using an value from the users data, which makes Power Bi an outlier right now where it pulls its locale info from the users browser, Is there any way to change this?

PowerBIEmbed does not support paginated report

Hello, is it possible to create a new component that embed paginated report? Based on the type definition, paginated report seems to use IPaginatedReportLoadConfiguration which is not part of supported type in PowerBIEmbed. If that is possible, can you let me know how to se it up? In addition the model IPaginatedReportLoadConfiguration is different from https://docs.microsoft.com/en-us/javascript/api/overview/powerbi/embed-paginated-report which includes type and embedUrl. Is that by design or the document is outdated?

Power BI React Client is not React at all?

Hello,
Is this a real React Client for Power BI?
It seems this "library" is just doing iframe for the hole BI page?
So there is no real React integration with BI product, it's just Iframe or I'm wrong?

image

Dynamic binding not working

I am trying to dynamically bind my report to a different dataset at runtime. I correctly create an embed token with the correct permissions but no matter what value i put in the datasetId attribute on the embedConfig it always uses the default dataset for the report.

Looking at the underlying javascript api (https://github.com/microsoft/PowerBI-JavaScript/wiki/Dynamic-Binding) it looks like embedConfig is not correctly mapped to the ' datasetBinding: {
datasetId: "xx",
}'
stucture on the config passed through.

thanks

Server Error ReferenceError: window is not defined

Hi, I'm developing an application in next.js (typescript) that uses powerbi-client-react to render powerbi dashboards in the application.

In a simple react application I can do what I want but would like to do it in next.js.

Here's the error and code:

Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
new WindowPostMessageProxy
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (5959:56)
wpmpFactory
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (8252:12)
new Service
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (10554:21)
Object../src/powerbi-client.ts
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (8858:15)
__webpack_require__
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (33:30)
<unknown>
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (97:18)
<unknown>
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (100:10)
webpackUniversalModuleDefinition
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (6:20)
Object.<anonymous>
file:///C:/Users/user/coding/project/node_modules/powerbi-client/dist/powerbi.js (13:3)
Module._compile
node:internal/modules/cjs/loader (1101:14)
import type { NextPage } from 'next'
import React, { useState} from 'react'
import Head from '../components/head'


import dynamic from 'next/dynamic'
import { EmbedProps } from 'powerbi-client-react';
import { models } from "powerbi-client";

const PowerBIEmbed = dynamic<EmbedProps>(() => import('powerbi-client-react').then(m => m.PowerBIEmbed), { ssr: false });

const Home: NextPage = () => {
  const reportId = process.env.REACT_APP_REPORT_ID;
	const accessToken = process.env.REACT_APP_ACCESS_TOKEN;
	const embedUrl = `https://app.powerbi.com/reportEmbed?reportId=${reportId}&groupId=${groupId]`
	const [config] = useState<models.IReportEmbedConfiguration>({
		type: 'report',
		embedUrl: embedUrl,
		tokenType: models.TokenType.Aad,
		accessToken: accessToken,
    	settings: {
      		panes: {
          		filters: {
              		expanded: false,
              		visible: false
          		}
      		},
		filterPaneEnabled: false,
		navContentPaneEnabled: false,
      	zoomLevel: 1,
		background: 1,
		customLayout: {
			displayOption: models.DisplayOption.FitToWidth
		 }
    	}
	});
  return (
    <div>
      <Head/>
      <main>
        <div>
        <PowerBIEmbed
				embedConfig = { config }
				cssClassName = { "report-style-class vh-100"}
			/>
        </div>
      </main>
    </div>
  )
}

export default Home

PowerBIEmbed display issue on switching to different tab before the Power Bi report is loaded/rendered

Steps to Reproduce the issue.

  1. Click on React Navigation link that will load the embeded PowerBi report
  2. Immediately move to a different tab on the browser (Before the report is loaded in step 1)
  3. Come back to you application after some time (by the time report should have loaded)
  4. Observed reported is not loaded as expected sometime showing empty body some time showing broken reports .

Note : If I am staying on the page till the report is rendered . Report generation is proper and there is no issue. Issue is occurring only when I am moving out of the page before Power BI report is fully generated

Error handling response: TypeError: Cannot set property 'blocked' of undefined

I downloaded the demo and ran it.

When I look at the console I receive an Error handling response after the rendering of the report.

Here is a copy of the console log:

Embedded object of type "report" received
[WDS] Live Reloading enabled.
Embedded object of type "report" received
Report has loaded
Report has rendered
reportEmbed?uid=5hdp6:1 Error handling response: TypeError: Cannot set property 'blocked' of undefined
at Object.preventFormFilling (chrome-extension://cpaibbcbodhimfnjnakiidgbpiehfgci/scripts/content-script.js:10:13632)
at Object.initFillForms (chrome-extension://cpaibbcbodhimfnjnakiidgbpiehfgci/scripts/content-script.js:10:14865)
at Object.secondBackgroundResponse (chrome-extension://cpaibbcbodhimfnjnakiidgbpiehfgci/scripts/content-script.js:11:1995)
at chrome-extension://cpaibbcbodhimfnjnakiidgbpiehfgci/scripts/content-script.js:8:11437
at chrome-extension://cpaibbcbodhimfnjnakiidgbpiehfgci/scripts/content-script.js:8:10668

dataSelected event listener does not fire on Select All and deselecting a filter

  • Selecting "Select All" in a slicer dropdown does not trigger the dataSelected event, however, selecting Select All following another slicer option triggers the event
  • Deselecting a filter from the slicer does not trigger the dataSelected event, however, selecting a filter then deselecting it in the slicer without closing the slicer menu triggers the event

Power Bi Action Bar Not Showing Export

Hi, I am trying to embed a report using powerbi-client-react and i am setting bars.actionBar.visible to true. I get an action bar but I am not able to get the export option. Below is an example of my code that I am running on the power bi sandbox.

Is this a bug with the react component? I am trying to get the action bar with the options presented from this docs: https://docs.microsoft.com/en-us/javascript/api/overview/powerbi/embed-for-organization. Has anyone successfully got this to work?

Using
"react": "^16.10.2"
"powerbi-client-reactt":"^1.3.3"

Code

let loadedResolve, reportLoaded = new Promise((res, rej) => { loadedResolve = res; });
let renderedResolve, reportRendered = new Promise((res, rej) => { renderedResolve = res; });

// Get models. models contains enums that can be used.
models = window['powerbi-client'].models;

// Embed a Power BI report in the given HTML element with the given configurations
// Read more about how to embed a Power BI report in your application here: https://go.microsoft.com/fwlink/?linkid=2153590
function embedPowerBIReport() {
    // Read embed application token
    let accessToken = EMBED_ACCESS_TOKEN;

    // Read embed URL
    let embedUrl = EMBED_URL;

    // Read report Id
    let embedReportId = REPORT_ID;

    // Read embed type from radio
    let tokenType = TOKEN_TYPE;

    // We give All permissions to demonstrate switching between View and Edit mode and saving report.
    let permissions = models.Permissions.All;

    // Create the embed configuration object for the report
    // For more information see https://go.microsoft.com/fwlink/?linkid=2153590
    let config = {
        type: 'report',
        tokenType: tokenType == '0' ? models.TokenType.Aad : models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: permissions,
        viewMode: models.ViewMode.Edit,
        settings: {
            bars:{
                actionBar:{
                    visible:true
                }
            },
            panes: {
                filters: {
                    visible: false
                },
                pageNavigation: {
                    visible: false
                }
            }
        }
    };

    // Get a reference to the embedded report HTML element
    let embedContainer = $('#embedContainer')[0];

    // Embed the report and display it within the div container.
    report = powerbi.embed(embedContainer, config);

    // report.off removes all event handlers for a specific event
    report.off("loaded");

    // report.on will add an event handler
    report.on("loaded", function () {
        loadedResolve();
        report.off("loaded");
    });

    // report.off removes all event handlers for a specific event
    report.off("error");

    report.on("error", function (event) {
        console.log(event.detail);
    });

    // report.off removes all event handlers for a specific event
    report.off("rendered");

    // report.on will add an event handler
    report.on("rendered", function () {
        renderedResolve();
        report.off("rendered");
    });
}

embedPowerBIReport();
await reportLoaded;

// Insert here the code you want to run after the report is loaded

await reportRendered;

// Insert here the code you want to run after the report is rendered

Access token

Hi,

In the demo we're fetching the token -- an essential key to render the embedded Power BI -- from a sample url in the mockSignIn function, but could you add information on how to get the token in a real case scenario? In this particular case, the Power BI is within an organization.

Thanks

Localization update

Hello,

I'm trying to dynamically change the locale of the embed configuration, I was wondering if it was even possible using for instance the updateSettings method of a report object?
It only works currently after the first initialization of the component.

The properties I'm trying to change:

{
  ...
  settings : {
    localeSettings: {
      language: "en",
      formatLocale: "en-GB"
    }
  }
}

Thanks!

Any plans for react-native?

I couldn't find any library for react-native integrating powerbi reports. Are there any plans for something for power bi with react-native?

Set filter configuration for report

Hi, my question is about configuring filters for the embedded reports.

Current behavior

The type of property filter in IEmbedConfiguration is
filters?: models.IFilter[];, and IFilter itself is

export interface IFilter {
    $schema: string;
    target: IFilterGeneralTarget;
    filterType: FilterType;
    displaySettings?: IFilterDisplaySettings;
}

For configuring any report's filter this set of property is not enough.

Expected behavior

For example for the basic type of filter, the set of properties is

export interface IBasicFilter extends IFilter {
    operator: BasicFilterOperators;
    values: (string | number | boolean)[];
    requireSingleSelection?: boolean;
}

So I would expect to have IReportLoadConfiguration where filters?: ReportLevelFilters[]; and

ReportLevelFilters = IBasicFilter | IBasicFilterWithKeys | IAdvancedFilter | IRelativeDateFilter | ITupleFilter | IRelativeTimeFilter.

Can you advise me on how to set filters properly for reports?

"ReferenceError: window is not defined" in Server Side Rendering

I've been using ReactJS.NET targeting build to client and server and facing the issue below:

An unhandled exception occurred while processing the request.
NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined
at eval (webpack-internal:///./node_modules/powerbi-client-react/dist/powerbi-client-react.js:1:208)
at Object../node_modules/powerbi-client-react/dist/powerbi-client-react.js (/app/ClientApp/dist/main-server.js:1397:1)
at __webpack_require__ (/app/ClientApp/dist/main-server.js:20:30)
at eval (webpack-internal:///./ClientApp/pages/DashboardPage.tsx:7:78)
at Object../ClientApp/pages/DashboardPage.tsx (/app/ClientApp/dist/main-server.js:291:1)
at __webpack_require__ (/app/ClientApp/dist/main-server.js:20:30)
at eval (webpack-internal:///./ClientApp/routes.tsx:13:78)
at Object../ClientApp/routes.tsx (/app/ClientApp/dist/main-server.js:356:1)
at __webpack_require__ (/app/ClientApp/dist/main-server.js:20:30)
at eval (webpack-internal:///./ClientApp/boot-server.tsx:24:66)
Current directory is: /app

Version:
"powerbi-client-react": "^1.1.0"

To repro, create a react project in VS from the built in template. Add the powerbi-client-react sample code provided in README.md.

When importing PowerBIEmbed in jest tests, fails right away with Cannot read property 'getRandomValues' of undefined

Versions:
"powerbi-client": "2.14.1"
"powerbi-client-react": "1.2.0"

So I have a react component that imports PowerBIEmbed as below.

import { PowerBIEmbed } from 'powerbi-client-react';

It works completely fine but when I try to reference the component with the PowerBIEmbed import it fails right away with the below:

TypeError: Cannot read property 'getRandomValues' of undefined

at Function.WindowPostMessageProxy.createRandomString (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack://window-post-message-proxy/dist/windowPostMessageProxy.js:125:1)
at new WindowPostMessageProxy (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/
/window-post-message-proxy/dist/windowPostMessageProxy.js:77:1)
at exports.wpmpFactory (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/src/factories.ts:24:10)
at new Service (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/src/service.ts:140:17)
at Object. (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/src/powerbi-client.ts:58:15)
at webpack_require (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/webpack/bootstrap e3359f5a2f7f804bc3cd:19:1)
at ../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/webpack/bootstrap e3359f5a2f7f804bc3cd:39:1
at ../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/powerbi.js:54:10
at webpackUniversalModuleDefinition (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/webpack/universalModuleDefinition:3:1)
at Object. (../../common/temp/node_modules/.pnpm/[email protected]/node_modules/powerbi-client/dist/webpack:/webpack/universalModuleDefinition:10:2)
at ../../common/temp/node_modules/.pnpm/[email protected][email protected]/node_modules/powerbi-client-react/dist/webpack:/powerbi-client-react/webpack/universalModuleDefinition:3:28
at Object. (../../common/temp/node_modules/.pnpm/[email protected][email protected]/node_modules/powerbi-client-react/dist/webpack:/powerbi-client-react/webpack/universalModuleDefinition:1:1)

PowerBIEmbed component is displaying the report with incorrect data

We are using PowerBI for report generation and we are using the PowerBIEmbed component to display those reports in our application. In our react application,

  1. we have different tabs based on different types of reports, and
  2. we have a set of filters exposed to users

So, based on the tab (i.e., report type) and filters selected we populate 'embedConfig'. We pass this config to the PowerBIEmbed component. Based on that appropriate reports are fetched and displayed in our application.

Issue: Under a particular tab modifying the filter values fetches the reports with correct data, whereas for selected filter values changing the tab is fetching the report with incorrect data.

Onservation: Upon debugging we observed that /querydata API calls internally called by powerbi-client-react are invoked with the right queries. But the data in the report fetched is incorrect.

May I know if we are doing something wrong? Or is it actually an issue? If so, could you help us resolving it?

how do you use hooks with eventHandlersMap?

Hello, I set an interval that refreshes the powerBi report after X amount of seconds.
Is there a way to use a reactHook to set state every-time the report renders. Counter will show zero.

     const [counter, setCounter] = useState(0);
    
       const updateCounter = () => {
       console.log("counter", counter);
         setCounter(counter + 1);
       };
    
       const handleRender = () => {
         updateCounter();
       };
    
       const eventHandlersMap = new Map([
         [
          "loaded",
          function() {
            console.log("Report has loaded");
          }
        ],
        [
          "rendered",
          function() {
            console.log("Report has rendered");
            handleRender();
         }
       ],

Calls to Refresh time out

It looks like calls to refresh our Power BI report take about 2 minutes. As such, they seem to time out/cancel before they ever finish running.

In turn, it looks like our token is not refreshing and the new access token is not being accepted. The end result is we see a lot of Canceled calls in the network tab and eventually we see the X's and errors fill the log.

How to print a report

I saw in powerbi-client

var element = document.getElementById('#myReport');
var report = powerbi.get(element);

report.print()
.catch(error => { ... });

do we have same in react-powerbi-client? like
<PowerBIEmbed
embedConfig={reportConfig}
eventHandlers={
new Map([
['loaded', function () {}],
['rendered', function () {}],
['error', function (event) {}],
])
}
cssClassName={'powerbi-embeded-style'}
getEmbeddedComponent = { (embeddedReport) => {

    embeddedReport.print();
  }}
/> 

DemoApp sample report throws error

The demo app sampleReport throws an error:

Response status code does not indicate success: 401 (Unauthorized).
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: Response status code does not indicate success: 401 (Unauthorized)
AdalServiceException: AADSTS7000222: The provided client secret keys are expired. Visit the Azure Portal to create new keys for your app, or consider using certificate credentials for added security: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials
Trace ID: db6f3573-78bf-4fc8-8aca-0d2932597600
Correlation ID: 6c707ff9-51eb-4485-a592-e11045e976a9

image

Using bootstrap mode causes exception related to bookmarks manager

As per the readme I am using bootstrap mode on the component so that the PowerBI embed loading spinner is shown while I am fetching an access token in the background.

This causes the bookmarks manager to throw an exception when I call report.bookmarksManager.getBookmarks();

The exception relates to the bookmark manager accessing a property on its internal config object which seems to be a cut down version of of the embed config passed to the react component.

It seems that when the props of the react component are updated to contain the full embed config object that configuration is not updated on the bookmark manager.

If I comment out the bootstrap code and only load the react component when I have the full config then the problem does not occur.

"refreshNotAllowed"

Hi,

When trying to update reports for different RLS users, this error messaged is returned:

detailedMessage: "Report refresh limit of 1 request(s) every 15 seconds reached. Please try again later."
message: "refreshNotAllowed"

Context:
We use

report?.refresh();

To refresh the reports for different users.
Receiving new config and updating the config didn't update the content of the reports, that's why after setting the new config we use refresh(), and that's when we receive the error when trying to update the report for different RLS users under 15 seconds.

 updateReportConfig({
        ...localConfig,
        embedUrl: reportConfig?.embedReport[0].embedUrl,
        accessToken: reportConfig?.embedToken.token
      });

Has anyone faced the same issue? Is there a better way to apply new config and refresh the content? ( report.relaod() didn't work either).

LayoutReport does not update with new settings with function updateSettings(settings);

Here is the code where I am using Power BI react component to render a blank report and then calling an action on loaded event handler. Action onLoaded fetches some JSON data and then create visuals on the report and then call renderVisuals with new settings. It looks like UpdateSettings function does not change the coordinates neither it changes the width/height correctly on resizing that I am trying to do. Here is the code for the component.

To look into actions, I am added the whole project on GitHub - https://github.com/nirjhar18/power-bi-updatesettings

`class EmbedChart extends React.Component {
componentDidMount() {
window.addEventListener(
"resize",
debounce((e) => {
this.updateDimensions();
}, 1000)
);
}
updateDimensions = () => {
this.props.actions.renderVisualsResize();
};
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}

render() {
return (
<>
<PowerBIEmbed
embedConfig={{
type: "report", // Supported types: report, dashboard, tile, visual and qna
id: REPORT_ID,
embedUrl: EMBED_URL,
accessToken: EMBED_TOKEN,
tokenType: models.TokenType.Embed,
permissions: models.Permissions.All,
viewMode: models.ViewMode.viewMode,

        settings: {
          panes: {
            filters: {
              expanded: false,
              visible: true,
            },
          },
        },
      }}
      eventHandlers={
        new Map([
          [
            "loaded",
            () => {
              this.props.actions.loadCharts();
            },
          ],
          ["rendered", () => {}],
          [
            "error",
            function (event) {
              console.log(event.detail);
            },
          ],
        ])
      }
      cssClassName={
        window.innerWidth > 1000
          ? "report-style-class"
          : "report-style-class-2"
      }
      getEmbeddedComponent={(embedObject) => {
        this.props.actions.getEmbeddedReport(embedObject);
      }}
    />
  </>
);

}
}`

Updating event handlers

Hey guys I'm just wondering about event handlers, So I've a function on the tileClicked event that calls a new tab (within app). that is supposed to open a report using the report id in the reportEmbedUrl, this works fine but the problem I have is the function doesn't receive the new state of the active tabs array which means if i go back and click on the same tile it opens a new tab instead of just activating the tab like I'm trying to achieve in this handleTileClick function.

So I guess what I'm asking is there a way to update the event handlers after the initial render?

Window is not defined

Hi,

I have installed powerbi-client-react, and have hardcoded in a valid token, report ID and embed URL.

I keep getting the following error, and I'm not sure why:

ReferenceError: window is not defined
    at Object.<anonymous> (...\powerbi-client-react\dist\powerbi-client-react.js:1:452)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.powerbi-client-react (...\.next\server\pages\reports\current-allocations.js:181:18)
    at __webpack_require__ (...\.next\server\pages\reports\current-allocations.js:23:31)
    at Module../pages/reports/current-allocations/index.tsx (...\.next\server\pages\reports\current-allocations.js:107:78)

Any help would be appreciated. Thanks!

Accessibility Issue

Between 480px-320px width some part of the action bar right icon buttons are getting cut.

image
asdfa

Power BI Report in SharePoint Team Site

Thank you for your work with this Power BI client react. We want implement a Power BI dashboard, during provisioning Team Site on SharePoint. Our business case is that we need to include/create Power BI report (web part or iFrame). How to add the report on a Client Site Page during provisioning the site template.

The challenge is to include Power BI reports, that incorporate SharePoint lists and/or excel files - add Power BI reports with relative URL provisioned site as data source for the reports.

Would appreciate tips if this is possible, and how we're able to do this!

Report.refresh() missing from readme?

Looking through the docs in this repo, there is no mention of report.refresh() https://github.com/microsoft/PowerBI-JavaScript/blob/master/src/report.ts#L515

For our app, doing a report.reload() is only grabbing the /modelsAndExploration endpoint, which was only updating the visuals on the report.

Doing a report.refresh() hits the actual querydata endpoint which is updating the report with the latest report data.

FYI for anyone that is looking into why a report.reload() is not updating the data in their report.

PowerBI reports don't render on Microsoft Edge 44

I get the message Power BI SDK is trying to post /report/load before iframe is ready. in Edge console. Report view only display spinning wheels. The report never loads. My Edge version is 44.18362.449.0.

Implementation different to demo app: I make the API call in a React useEffect hook and update PowerBIEmbed embedConfig.

This works fine in Chrome.

Update the report filters

Is it possible to update the report filters like that?

image

The image above is from pbi playground.

image

In the image above im trying to update the report filters in React, but the second argument of the updateFilters function doesnt have the properties operator and values anymore.

Could someone please help me? Thank you all.

Default Slicer Values to be changed dynamically based on the selection of filters by users.

Business Requirement: Default Slicer Values to be changed dynamically based on the selection of filters by users.

Challenge: PowerBI does not support the default Slicer value changes based on filter change from front end.

Workaround: Pass the default values to slicers through an API from backend

Issue: While passing the values to slicer from API, default values are not updating in Power BI. Following are the procedure that we are following.

  1. Created an API, which features the default value for every product

  2. Based on the default values fetched, we create slicer configuration in the following format.
    [{
    "selector": {
    "target": {
    "table": "table_name",
    "column": "column_name"
    },
    "$schema": "http://powerbi.com/product/schema#slicerTargetSelector"
    },
    "state": {
    "filters": [{
    "target": {
    "table": "table_name",
    "column": "column_name"
    },
    "$schema": "http://powerbi.com/product/schema#basic",
    "operator": "In",
    "values": ["domain.com"],
    "filterType": 1,
    "requireSingleSelection": true
    }]
    }
    }]

  3. Pass the above config as a slicers prop to the "PowerBIEmbed" component under "powerbi-client-react" (PowerBI react library). We are using the latest version (1.3.3)

Any plans for Vue.JS client?

Do you have plans for other client side libs (Vue.JS, Angular)? If so, how can we contribute since this repo is specifically for React.

Embedded power BI iframes don't do not have accessible names

I have a power BI report that I am embedding on our web page. The custom visual and the report itself are iframes. Our accessibility team used accessibility insights for web version 2.23.0 and detected that we violated the frame-title rule where there is no accessible name in the iframes.

We tried updating to the latest powerbi-client-react version 1.3.1 but the issues persists.

See below for the screenshot including the accessibility details.

The right hand bang error is for the overall iframe and the left hand hang error is for the custom visual in our Power BI report.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.