I am new to SPFx with react. I am creating a webpart to include a dropdown to have options from a choice column of a sharepoint online list. When loaded the dropdown from a static option values it works fine, however when loaded from a choice field from SPList which is set to state variable it gives the error message as
requestTypeOptions is the only property in state.
Below are the code files DemoFormBaseWebpart.ts
export default class DemoFormWebpartWebPart extends BaseClientSideWebPart<IDemoFormWebpartWebPartProps> {
public render(): void {
const element: React.ReactElement<DemoFormWebpartProps> =
React.createElement(DemoFormWebpart, {
description: this.properties.description,
context: this.context,
});
ReactDom.render(element, this.domElement);
}
DemoFormWebpart.tsx
import * as React from "react";
import styles from "./DemoFormWebpart.module.scss";
import { IDemoFormWebpartProps } from "./IDemoFormWebpartProps";
import { escape } from "@microsoft/sp-lodash-subset";
import {
Dropdown,
IDropdownOption,
IDropdownStyles,
} from "office-ui-fabric-react";
import { IDemoFormWebpartState } from "./IDemoFormWebpartState";
import { sp } from "@pnp/sp";
import "@pnp/sp/lists";
import "@pnp/sp/webs";
import "@pnp/sp/items";
import "@pnp/sp/fields";
import { IList, List } from "@pnp/sp/lists";
export default class DemoFormWebpart extends React.Component<
IDemoFormWebpartProps,
IDemoFormWebpartState
> {
private testList: IList;
constructor(
props: IDemoFormWebpartProps,
state: IDemoFormWebpartState
) {
super(props);
sp.setup({
spfxContext: this.props.context,
});
this.setState({
reuestTypeOptions: [],
});
}
componentWillMount() {
this.testList = sp.web.lists.getByTitle("TestList");
const choiceField =
this.testList.fields.getByInternalNameOrTitle(
"choiceField"
);
choiceField
.select("Choices")
.get()
.then((optionsData) => {
if (optionsData["Choices"]) {
const choiceOptions = optionsData["Choices"].map(
(item, i: number): IDropdownOption => {
return { key: item, text: item };
}
);
this.setState({
reuestTypeOptions: choiceOptions,
});
}
});
}
public render(): React.ReactElement<IDemoFormWebpartProps> {
return (
<div className={styles.demoFormWebpart}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<Dropdown
id="ddlRequestTypes"
label="Request Types"
options={this.state.reuestTypeOptions}
/>
</div>
</div>
</div>
</div>
);
}
}
Noticed that options are loaded in the state variable, however render method is executed before loading of state variable.
Not sure what is happening. Please help me on this. Thank you. Below is package.json