skip to Main Content

actually Im working with SPFX webpart using React, really dont understand what is the issue here, but when I debug it shows the blow screenshot.

trying to get the SP list items in SPFX webpart using React, during the map it getting error.
please assist me using the below piece of code.

[undefied]
public render(): React.ReactElement<IGetSpListItemsProps> {
    return(
    <div className={"styles.welcome"}>
      <table >
    {
    this.state.listitems.map(function (listitem, listitemkey){
    let fullurl: string = `${GetSpListItems.siteurl}/lists/SampleList/DispForm.aspx?ID=${listitem.ID}`;
    return(
    <tr>
    <td><a className={styles.label} href={fullurl}>{listitem.Title}</a></td>
    <td className={styles.label}> {listitem.ID}</td>
    </tr>)})}
    </table>

Here is the video where I have gone through as per the same I have followed but when I try it shows undefined error
text

2

Answers


  1. change your code to this:

    {this.state.listitems && this.state.listitems.length>0 && this.state.listitems.map(function (listitem, listitemkey){
        let fullurl: string = `${GetSpListItems.siteurl}/lists/SampleList/DispForm.aspx?ID=${listitem.ID}`;
        return(
        <tr>
        <td><a className={styles.label} href={fullurl}>{listitem.Title}</a></td>
        <td className={styles.label}> {listitem.ID}</td>
        </tr>)})
    }
    
    Login or Signup to reply.
  2. map method belongs to array in Javascript. In your case, value of variable is undefined and for that variable value map method is being applied. Thus, you are seeing that error as being an invalid value for map method.

    In order to resolve/prevent this error, what we can do is that, before assigning variable to map method, we will do separate conditional check for that variable value to make sure that it will be a valid array. With that, you won’t be having that error.

    import React, { Component } from "react";
    
    export default class WelcomeTable extends Component {
      render() {
        const { listitems } = this.state;
        const items =
          listitems && Array.isArray(listitems) && listitems.length > 0
            ? listitems
            : [];
    
        return (
          <div className={"styles.welcome"}>
            <table>
              {items.map(({ ID, Title }) => (
                <tr key={ID}>
                  <td>
                    <a
                      className={styles.label}
                      href={`${GetSpListItems.siteurl}/lists/SampleList/DispForm.aspx?ID=${ID}`}
                    >
                      {Title}
                    </a>
                  </td>
                  <td className={styles.label}> {ID}</td>
                </tr>
              ))}
            </table>
          </div>
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search