Category: O365

Getting started with Redux in SharePoint Framework – Part 2

As you can read in part 1 we are converting a ‘plain’ React SPFx webpart to a version with Redux to have an external stage management mechanism.

We are starting from the basic idea of having a webpart that displays a list of sessions of a SharePoint Saturday. Next to displaying the sessions, the user can also remove a session from the list and add a new session the list.

To convert this to a working Redux application, we need to follow the next steps:

  1. Install necessary npm packages
  2. Create and configure store
  3. Create actions
  4. Create reducer
  5. Decouple components from each other (remove callback functions)
  6. Connect components to the reducer
Overview of the webpart

NPM packages

Basicly you need to install Redux with the following command

npm install redux

You also needs to add the React binding for Redux

npm install react-redux

Finally you need to install Redux-Thunk for middleware operations (more information later on this post).

npm install redux-thunk

Create and configure the Redux store

Using Redux, the store is THE place where all the application data (state) is stored. The only way to change the data is to dispatch an action and to process that action with a reducer.
Note: In comparison to other state managers Redux only has one store.

Creating the store is very simple. Create a new folder called store (not mandatory but recommended), create a new file configurestore.ts and add the following code to the file:

After creating the store, the application and components need to know that there is a store and that it can be used to save, update and retrieve data.
This needs to be done in the top level component of our component structure => in our example ReduxSessionWp.tsx. Call the configureStore() function and pass it to the Provider.

A Provider is a wrapper component that makes it possible for the nested components (the ‘normal’ components of our application) to access the store by using the connect() function.

Actions

Now that the basic one-time-only configuration part is over, we can start defining the actions. Actions are pieces of information that the application and individual components can send to the reducer to update the global application state.

An action is an object built up with 2 basic properties:

  • Type
  • Data (string, number, complex object…)

When a component wants to update the global application state, it needs to dispatch an action (for example: {Type: “Add_Session”, Data: {speaker:”Yannick”, session: “ABC”}}). The reducer will pick up the trigger and execute that specific action.

For each action that is possible within your application, you need to define it by using the ActionTypes. Basically it needs to be a const string but you can also manage it with an enum for each possible action. By using the enum you can reuse it more easily in your application.

Dispatching an action is possible by calling the corresponding function. Those functions are called action creators. The only thing they do is create an action object of type and data.

Reducer

The only location where the global application state in Redux can be changed is inside the Reducer.

The reducer is composed of pure functions that respond to the actions that are sent to the store. It will take in the old state and an action and returns the new (updated) state to the store.

Note: Pure functions are functions that return the same output for the same given input, and don’t produce any side-effects.

If we take a look at the code of the reducer it ‘just’ contains a large switch statement for each possible action(Type).

First, the reducer creates a new clone of the current/old state. Next the switch decides, based on the action.type, which specific action needs to be done against the state.

Decoupling of components

In our React example some components were coupled with each other to pass data and functions from one component to another. Now with Redux, that coupling of components becomes unnecessary. We have the possibilty to individually couple/connect the components to the state.

Connecting components

At this moment the components are unaware of the global application state and can’t update it with new information. Connecting a component to the store is done in multiple steps.

mapStateToProps

This function will connect specific (you can define which ones) information from the state to properties of the component. So instead of passing data from one component to another we now connect directly to the data.

Your application state (probably) contains a lot of data/objects, so loading all those objects to every component is overkill. Redux is smart enough to provide the possibilty to only load the objects you need. In the example above we only load the sessionItems from the state.

As with the local state of components, when there is a change of the application state, every component (that is connected to that specific updated object) will immeditialy receive the updated object.

mapDispatchToProps

Next to passing the objects between components in the React-only example, we also passed callback functions between components. This becomes also unnecessary with Redux and mapDispatchToProps. It allows the component to load the (pure function) actions into the properties of the component. This allows the component to simply call the action by this.props.ACTION.

Connect

So now all the converting is done of the data and functions inside the component, the only thing you need to do is one simple line of code for each component (that needs to be connected):

It let’s the component listen to the store and provides all the data and functions it needs. The properties mapStateToProps and mapDispatchToProps are optional. So it is possible to have components only having dispatched actions (Form) and components only reading data from the store (SessionList).

Middleware for async calls

As you maybe noticed, the last thing we did not yet talk about, was the async call to our API.

By default actions are synchrounsly in Redux. To achieve an async action, like for example calling an API, we need to implement Middleware. There are two popular libraries available for this, I have choosen Thunk.

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

https://github.com/reduxjs/redux-thunk

Here is a nice animation availble which explains this concept:

When a view (component) triggers an action, the Middleware takes care of your API calls and updates your state.

How to implement?

Maybe you noticed it already, when I configured the store, I already included the Middleware. It is actually as simple as importing applyMiddleware (redux module), importing thunk and ThunkDispatch (redux-thunk module), and passing through applyMiddleware(thunk) in the createStore function.

Next, create a new file AsyncFunctions.ts under the actions folder. This files contains the httpClient call to the API and will dispatch (after retrieving the data) the addNewSession action. This action is exactly the same as we use inside the form component.

Recap

Tadaaa! Normally after following all the previous steps, you should have a working Redux version of your application.

The initial setup looks very difficult, especially the first time, but eventually it saves you a tremendous lot of work compared to when you needed to handle all the state changes by propagating the props and functions.

Feel free to contact me by my blog, Twitter, LinkedIn.. if you have any questions or comments!

Extra references can be found here:

https://github.com/yborghmans/SPFxReduxDemo
https://redux.js.org/
https://github.com/reduxjs/redux-thunk

Getting started with Redux in SharePoint Framework – Part 1

Finally I managed to write this blog post. It took me a couple of attempts, but after my session at SPS Doha I was encouraged enough to finish the blog post and provide it to you.

This post will take you step by step into the wonderful world of Redux, React and SharePoint Framework (SPFx). It’s built up by my own experiences of a pretty large SPFx project where Redux was used to handle the states of numerous (+50) components.

Why using ‘something’ like Redux?

The states within my first SPFx projects were pretty much easy to handle and we had a good overview of how they handled changes in the components. But the latest project I did with SPFx was really different than the previous ones. This time there were just too many components to handle and too much data to pass trough between the components. This means that it would cost us a lot of time to think about how to pass properties between components and how to traverse between the different levels of components.

And that’s when Redux came in the picture. Without Redux, as an ‘external’ state management mechanism, handling those state changes would be close to impossible.

Let’s take this simple example (which will be used throughout this post) where we have an SPFx webpart that displays the sessions of SPS Doha. Besides showing the list, it also allows the user to add and remove sessions to and from the list. Pretty simple example, but it does help to explain the dependencies between the components.

Overview of the simple application

In the Webpart component we will store a list containing all the sessions. Those sessions are fetched from a specific API (async) when the webpart is loading.

The list of sessions is passed through to the ‘Session list’-component where every item is displayed with the ‘Session item’-component. That component also contains a remove icon to remove that item from the list (which is stored in the webpart component).

On the other hand we have the input form, that component simply contains two input fields (title and speaker), and a submit button. The button is the trigger to add a new item in the list (again, that list is stored in the webpart component).

As you probably know, this means that we need to pass functions between the components containing a callback to update the list in the webpart component.
For example:

Coding of (React) example

So how do we get the example of the session list working with just ‘plain’ React code in SPFx?

Webpart/Container component

In our main component we create multiple things:

  • Function to retrieve the data from the API
  • Function to add an item to the list
  • Function to remove an item from the list
  • Rendering of the subcomponents

The most important part of this component is the rendering function. Here we see the callback functions being passed on to the child components. We also see that SessionList retrieves the local state variable sessionItems. This variable/list will be updated by the callback functions _AddItem and _DeleteItem


The other code can be found here: https://github.com/yborghmans/SPFxReduxDemo/tree/master/ReactSession

Form component

Next we have the form component where we can add new items to the list. When a user clicks the button, the _handleAddButtonClick function will call the callback function handleAddItem from the properties of the component. This way the data will be propagated up towards the main component.

SessionList component

Not really magic stuff in this component, just simply a .map iteration over the sessionItems and loading the SessionItem component. The only thing to notice is the propagation of the callback function.

SessionItem component

In this component we have the option to delete the specific item from the list of sessions. This is made possible by using the callback function which is provided in the props of the SessionItem component (onDeleteItem). Calling this will trigger the main component and remove the item from the state.

Overview/conclusion React example

So as you can see in the picture below, we have to propagate a lot of data and callback functions up and down to let the application respond to the user input. In this small example it is still easy to manage and sustain the global state of the application. But when you have many more levels of components and a more complex data structure, it can easily become unsustainable to manage the global state.

And that’s where Redux comes in the picture; to provide an alternative way of managing the global state. It will create a new global state ‘beside’ your application and a component can connect to it when it’s necessary to retrieve or update data. If a component has nothing to do with data, it remains independent and unaware of the global state.

https://hackernoon.com/restate-the-story-of-redux-tree-27d8c5d1040a

Converting to Redux

In the following post I will explain step by step how to convert this example to Redux. It will basically contain the following parts:

  • Installing and creating the basic Redux parts
    • Store
    • Reducer
    • Actions
    • ApplicationState
  • Decouple components from each other
  • Connecting components to the store
  • Middleware

Getting started with Redux in SharePoint Framework – Part 2

Install & Uninstall SharePoint apps by code announced at ESPC 2017

Today at ESPC 2017, Vesa Juvonen announced the availability of an endpoint on SharePoint Online to install, uninstall, deploy, retract, upgrade, and remove SharePoint apps programatically.
As I was thrilled by the announcement, I immedialty tested it out on my development environment with this blogpost as result (for the items I could test by myself).

So, wich information do we get from the endpoint, which actions can we execute?

Get apps

First of all, the endpoint itself looks like: _api/web/tenantcatalog
Using that endpoint (GET) will provide the following result:

The bold ID is the identifier which we have to you to execute the other actions like install, uninstall…

Other properties are also returned like:

  • AppCatalogVersion: showing the version of you app in the appcatalog (so not the installed version).
  • CanUpgrade: true or false, depending if you can upgrade you app to the latest version.
  • Deployed: if the app is deployed on the current site for where you are executing the call.
  • InstalleVersion: the current installed version of the app, can be lower than the appcatalogversion.
  • IsClientSideSlution: if the application is a SPFx solution.
  • Title: the title of the application.

 

POST actions

The following actions gives you the posibility to perform some usefull actions with your app and your app package at sites and at the app catalog.
As you can notice, the add-command isn’t described below. That’s for the simple reason I can’t get it working. For that call I have to wait for the official documentation of Microsoft, so it is clear which body has to provided to add an app to the app catalog.

Update (18/11/2017): The official documentation is out and can be found (together with the PNP Powershell cmdlets) at: Application Lifecycle Management (ALM) APIs

Install app

To install an app, you have to use the following endpoint: _api/web/tenantappcatalog/AvailableApps/GetByID({id})/Install
Where {id} has to be replaced with guid’27a768cb-89fc-45ba-939c-6ac4cf617f7a’
Providing the correct X-RequestDigist header will result in an ‘200 – OK – response’, and the app will be installed

Result (200 – OK):

Uninstall app

Pretty much the same as installing an app, but instead of /install, you have to use (so obvious) /uninstall.

Result (200 – OK):

Upgrade app

If there is a newer version in the appcatalog available for your specific app, you can use this action to upgrade to app to the latest version (and again the same as with install and uninstall):

Result (200 – OK):

Remove, retract, deploy

For remove, retract,  and deploy you have to go to the app catalog site collection (there were the app packaged where added).
First you have to retract the app from your tenant by the following action/command:

To redeploy the app to your tenant you can use

To entirely remove the app from the app catalog you can use the following action/command:

 

Start your MS Flow from within the new SharePoint column formatter

At Ignite, Microsoft announced the new column formatter for SharePoint online. It provides the flexibility to format your columns based on your data.

SharePoint list with three columns formatted
https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/column-formatting

Lincoln DeMaris (BRK3252) explained how the formatting worked with a lot of useful demos. One of them was a button/link in a column that launches an MS Flow for that specific item in your list. Unfortunately, the docs.microsoft.com article does not provides the JSON yet, but you can copy paste it from here. The only thing you have to do is to create an MS flow, copy paste the GUID, and give it a relevant name in the JSON. If you want to format the column, you can take a look at the documentation of Microsoft on: Get started with column formatting (docs.microsoft.com)

Important note: The flow has to be able to start on it’s own. This means that the trigger for the flow has to be for example the “For the selected item”-trigger of the SharePoint repository. Otherwise the panel on the right won’t show up and the console logging will show you that the flow can’t be executed.

And example of a working flow:

Extra information:

Use column formatting to customize SharePoint (docs.microsoft.com)

Geek out with the product team on SharePoint lists and libraries (Youtube)

How to activate modern pages on a classic team site

Recently I was searching for how to get the new Modern Pages in an old classic team site, which was created a couple of years ago in SharePoint Online.
New modern team sites, Groups and Communication sites are already having the new Modern Pages, but the old ones are still stuck with the old fashioned pages like SP2013.
As I’m missing all the new features and eager to improve our old home page, I went looking for the trigger that defines if SharePoint creates a modern or classic page.

First I have noticed that there was an extra contenttype in the Site Pages library of Modern Team sites. Site Pages is the contenttype which is used to create the new Modern pages.

Screenshot from the Site Pages library on a Communication site

 

 

Adding this contenttype to the old Site Pages library went fine but creating a new page, based on the Site Page contenttype, results in the following error:

 

 

After comparing the activated features of the old team site and the Modern Team site I bumped into the following feature:

 

 

 

And as obvious as the name is, the Site Pages feature will activate the modern pages for the old team sites and let you enjoy all the new functionalities that are provided by the modern pages.

From now on, clicking on “Add a page” will create a modern page:

 

Enjoy!

GiphyBot in Teams

One of the most requested features @Ventigrate is a proper implementation of Giphy in Microsoft Teams. Microsoft did provide a solution to that request but it is not  as user friendly as it is in Slack.

That’s why I developed a Microsoft bot that you can use to get a random gif back by providing a keyword. I published the bot to azure and thanks to the (new) posibility of sideloading bots in Teams, it possible to activate and use it on your own tenant (see “How to install it?)”.

What’s different between Slack, Teams and Giphybot?

In Slack, the implementation of Giphy provides a random gif by typing ‘/Giphy {keyword}’ into a channel. That’s way more quicker and funnier than the implementation of Microsoft in Teams

Microsoft’s implementation requires that you click on the gif icon, provide a keyword and select a specific gif. The akward moment of waiting, of which gif is showing up, is lost and users stop using Giphy in Teams.

The implemention I made gives users the possibility of getting random gifs back by mentioning the bot in a channel: ‘@GiphyBot {keyword}’. The bot will reply with a random gif according to your keyword.

How to install it?

  1. Create a new manifest.json file with the following lines of code [Note: make sure the ID is correct: 231f435f-4d49-47a4-a26f-fc7d6f91cbee]
  2. Zip the manifest.json file
  3. Go to Teams an on the team you wish to load it, click on the overflow (“…”), and select View team..
  4. Select the Bot tab, then click on “Sideload a bot or tab” on the lower right.
  5. Browse to and select your zip package from your PC.
  6. You will see your sideloaded bot or tab in the list.

From now on you can use the bot! Have fun!

 

Please let me know what you think about this bot! And keep following (@Yborghmans) for the next blog post where I explain the development of the GiphyBot.

 

More information about the bot framework: