0
import { Web } from "sp-pnp-js";
    import pnp from "sp-pnp-js";


interface ISPVehicule {
  Title: string;
  Marque: string;
  Modele: string;
  Vitesse: string;
  Poid: string;
}


export default class ReactPnP extends React.Component<IReactPnPProps, {}> {

  private vehiculeList:  ISPVehicule[];
  private web;

  constructor(props)
  {
    super(props);
    this.web = new Web(this.props.contextUrl);

    this.web.lists.getByTitle("Voitures").items.get()
      .then((vehicules: ISPVehicule[]) => 
      {
        this.vehiculeList = vehicules
      });

      console.log("vehicule : " + this.vehiculeList);
  }
....

I would like to store the Get Method result in the VehiculeList property. However, it does not work the way I have done it. In fact, I am getting this error message:

"vehicule : undefined"

Do you know what I am doing wrong?

Eventually, I would like to use this property to display its content by injecting the following code in the Render Method :

{this.vehiculeList.map((vehicule) =>{ return (<div>{vehicule.Title}</div>); } )}.
1

You should be using state instead of private property. When property is changed React does not know about it and does not re-render the component. When the state is changed in componentDidMount it will re-rende the component.

import { Web } from "sp-pnp-js";
import pnp from "sp-pnp-js";

interface ISPVehicule {
  Title: string;
  Marque: string;
  Modele: string;
  Vitesse: string;
  Poid: string;
}

interface IState {
  vehiculeList: ISPVehicule[];
}

// Define some state object instead of empty object {}
export default class ReactPnP extends React.Component<IReactPnPProps, IState> {
  private web;

  public render(): JSX.Element {
    return (
      <div>
        {this.state.vehiculeList.map((vehicule: ISPVehicule) =>
          <div>{vehicule.Title}</div>
        )}
      </div>
    );
  }

  // Http call when component mounts
  public componentDidMount() {
    this.web = new Web(this.props.contextUrl);

    this.web.lists.getByTitle("Voitures").items.get()
      .then((vehicules: ISPVehicule[]) => {
        // Use callback for reading the value from this.state
        this.setState({ vehiculeList: vehicules }, () => {
          console.log("vehicule : " + this.state.vehiculeList);
        });
      });
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.