Forum Discussion
Mike Jansen
Oct 12, 2017Iron Contributor
spfx React > REST API > Map search results
I have a woking example where I map (rest) search results to an object like this: export interface IReactGetItemsState{
items:[
{
"EmployeeName": "",
"Employ...
- Oct 23, 2017
I had to create my own version of the web part to test the code. This works for me :-)
import * as React from 'react'; import styles from './HelloWorld.module.scss'; import { IHelloWorldProps } from './IHelloWorldProps'; import { escape } from '@microsoft/sp-lodash-subset'; import { SPHttpClient, SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http'; export default class HelloWorld extends React.Component<IHelloWorldProps, any> { constructor(props) { super(props); this.state = { items: [], }; } private search(): Promise<any> { const spSearchConfig: ISPHttpClientConfiguration = { defaultODataVersion: ODataVersion.v3 }; const clientConfigODataV3: SPHttpClientConfiguration = SPHttpClient.configurations.v1.overrideWith(spSearchConfig); var url = "https://xxx.sharepoint.com/sites/vmf-lab/_api/search/query?querytext='ContentType:Kvalitetsdokument'&selectproperties='Title,RefinableString05,CreatedBy,Created'&rowlimit=500"; //this.properties.siteUrl + "/_api/web/lists"; return this.props.context.spHttpClient.get(`${url}`, clientConfigODataV3).then((response: SPHttpClientResponse) => { if (response.ok) { return response.json(); } else { console.log("WARNING - failed to hit URL " + url + ". Error = " + response.statusText); return null; } }); } componentDidMount() { this.search().then((response) => { this.setState({ items: response.PrimaryQueryResult.RelevantResults.Table.Rows }); }); } public render(): React.ReactElement<IHelloWorldProps> { return ( <div className={styles.helloWorld}> <div className={styles.container}> {this.state.items.map(row => <div className={`ms-Grid-row ${styles.row}`}> <div className={`ms-Grid-col`}> {row.Cells.map(col => <div>{col.Key} - {col.Value}</div> )} </div> </div> )} </div> </div> ); } }Hope it works.
Mike Jansen
Oct 12, 2017Iron Contributor
Things are a bit more clear but my main issue is the mapping of my query results to the "Item" object.
I try:
items: resultData.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results.Cells
But I need to solve it some other way. Still do not know howto.... sorry.
An example would be great....
Mike Jansen
Oct 19, 2017Iron Contributor
Can someone help me out on this? Still not able to solve it.
Thanks, Mike
- Maggan WåhlinOct 19, 2017Iron ContributorHi Mike,
Could you post your code? Meanwhile, you could try getbyid(<listguid>) instead of the list title in the REST query. It's a long shot... I always use Postman to test my queries, it's a Chrome app.- Mike JansenOct 19, 2017Iron Contributor
Hi Maggan Wåhlin (I should buy you a beer for your help, already).
The complete code is this:import * as React from 'react'; import styles from './ReactGetItems.module.scss'; import { IReactGetItemsProps } from './IReactGetItemsProps'; import { escape } from '@microsoft/sp-lodash-subset'; import * as jquery from 'jquery'; export interface IReactGetItemsState{ items:[ { "RefinableString10": "", "CreatedBy": "", "Created":"" }] } export default class ReactGetItems extends React.Component<IReactGetItemsProps, IReactGetItemsState> { public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){ super(props); this.state = { items: [ { "RefinableString10": "", "CreatedBy": "", "Created":"" } ] }; } public componentDidMount(){ var reactHandler = this; jquery.ajax({ url: "https://Blabla.sharepoint.com/sites/bla/_api/search/query?querytext='ContentType:Test_matters'&selectproperties='RefinableString10%2cCreatedBy%2cCreated'&rowlimit=500'", type: "GET", headers:{'Accept': 'application/json; odata=verbose;'}, success: function(resultData) { reactHandler.setState({ items: resultData.PrimaryQueryResult.RelevantResults.Table.Rows }); }, error : function(jqXHR, textStatus, errorThrown) { } }); } public render(): React.ReactElement<IReactGetItemsProps> { return ( <div className={styles.panelStyle} > <br></br> <br></br> <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API & React JS </div> <br></br> <div className={styles.headerCaptionStyle} > Employee Details</div> <div className={styles.tableStyle} > <div className={styles.headerStyle} > <div className={styles.CellStyle}>Employee Name</div> <div className={styles.CellStyle}>Employee Id </div> <div className={styles.CellStyle}>Experience</div> </div> {this.state.items.map(function(item,key){ return (<div className={styles.rowStyle} key={key}> <div className={styles.CellStyle}>{item.RefinableString10}</div> <div className={styles.CellStyle}>{item.CreatedBy}</div> <div className={styles.CellStyle}>{item.Created}</div> </div>); })} </div> </div> ); } }The line: "items: resultData.PrimaryQueryResult.RelevantResults.Table.Rows" is the problem.My Json return is not formatted good enough to do the binding like this.For example, if I need the value of "RefinableString10" I have to dig deep into the json to get it:"resultData.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i].Cells.results[2].Value"My start was this example: https://gallery.technet.microsoft.com/office/Create-SPFx-Web-Part-to-d5282a5fMy query is fine. In debug I see the expected results in "resultData"All I did was change the query to get some other results.- Maggan WåhlinOct 19, 2017Iron ContributorI tried a similar query in Postman and now I see what you mean... To get a "clean" JSON, remove odata=verbose from the accept header. It will remove all the metadata you don't need 😊
https://blogs.office.com/en-us/2014/08/13/json-light-support-rest-sharepoint-api-released/?eu=true
Cheers 😊