Home > CMS- Content Management System > Sharepoint > Getting the current context in SPFx service and get the SharePoint List items

Getting the current context in SPFx service and get the SharePoint List items

Hello,

In this article, I will show you how to get the current context of the site and pass it to services. In the traditional method, we were getting the Current Context of the site from SP.ClientContext or using Rest API.

I have created a React-based SPFx Web part. I have different components, services and model folder. I want to pass the current context to my service, what I observe you can current context only in root or ‘*’WebPart .ts file. So get the value from the root component and pass to my services.

It helps to maintain all your services in one place, it makes code easy to maintain, understandable and DRY.

  1. So first get the Current context from the root file
  2. ReactHelloWorld is my child components, where I create Props and create a new object of spservices class 
     If you console it will return the whole object of the current context SPHttpClient, PageContext
  3. We are importing  the WebPartContext class from the ‘@microsoft/sp-webpart-base package’ module and pass to context props, Add in ReactHelloWorld
  4. First, import the SPHttpClient class from the ‘@microsoft/sp-http package’ module and the WebPartContext class from the ‘@microsoft/sp-webpart-base package’  module in the spservices file

    see the console results in below screenshot

  5.  Declared the getContentTypeItems function in spservices, I added the IContentTypeMasterListItem as a model while getting the response
  6. Call the below function in componentWillMount() react lifecycle methods and perform the your actions.

Hope you find it helpful. If you liked this article, then please share and comment.

This Article is TAGGED in , , , . BOOKMARK THE permalink.

Avatar photo
Chintan Upadhayay
I am a senior web developer with more than 4+ years experience in WordPress, PHP, MySQL, HTML, CSS, jQuery and other web technologies. I am the beginner in SharePoint and Learning SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">