Skip to main content
3 of 3
edited tags
Ganesh Sanap - MVP
  • 46.4k
  • 22
  • 31
  • 63

How to retrieve a specific item with SPFx and Query in the React Framework SharePoint Online

I would like to get a specific item by ID. I'm really stuck how I can retrieve this item.

I called the list and tried to save it in an object and then should in the render() function.

Here is my code so far:

import * as React from 'react';
import styles from './Webpartprojectsw.module.scss';
import { ISolypListItemState } from './ISolypListItemState';
import { IWebpartprojectswProps } from './IWebpartprojectswProps';
import { escape } from '@microsoft/sp-lodash-subset';
import * as jquery from 'jquery';
import { TextField, PrimaryButton } from '@fluentui/react';
import {ISPHttpClientOptions, SPHttpClient,SPHttpClientResponse} from '@microsoft/sp-http';
import { ISolypListItem } from './ISolypListItem';

  export default class Webpartprojectsw extends 
React.Component<IWebpartprojectswProps,ISolypListItemState> {

static websiteurl: string="";
public constructor(props:IWebpartprojectswProps, state: ISolypListItemState){
   super(props);
   this.state={
       status:"ready",
       SolypProjectItem:{
           Id: 0,
           Title: "",
           StartDate:"",
           EndDate:"",
           ProjectPhase:"",
           TrafficLight:""

       }
   };
Webpartprojectsw.websiteurl=this.props.websiteurl;
 };


 public componentDidMount(): void {
   let reactcontexthandler = this;
   console.log("Link zur Seite:" + Webpartprojectsw.websiteurl);
   jquery.ajax({
 url:`${Webpartprojectsw.websiteurl}/_api/web/lists/getbytitle('ProjectStatusList')/items(1)`,
        type: "GET",
        headers: {'Accept':'application/json;odata=verbose;'},
        success: function (resultData){
          console.log(resultData);
          reactcontexthandler.setState({
          SolypProjectItem: resultData.d.results[0]
          });
        },
        error: function (jqXHR,textStatus,errorThrown){

        }

   });

 }



public render(): React.ReactElement<IWebpartprojectswProps> {
return (
   <div>
     {this.state.SolypProjectItem.Title}
     {this.state.SolypProjectItem.StartDate}
     {this.state.SolypProjectItem.EndDate}
   </div>      
      
   );
  }

 }

Here is my interface:

export interface ISolypListItem{
Id: number;
Title: string;
StartDate: string;
EndDate: string;
ProjectPhase: string;
TrafficLight: string;
}

and my State:

import { ISolypListItem } from "./ISolypListItem";

export interface ISolypListItemState{
   status: string;
  SolypProjectItems: ISolypListItem[];
  SolypProjectItem: ISolypListItem;
}

I don't exactly how I can put the retrieved element into the object and then use in the HTML.