I'm new to react concept, I don't understand why I lose the value of the state after the .then()
I lose the ISPList state value but I did set state :(
appreciate any help.
export default class Cartable extends
React.Component<IMainCartableProps, ICartableState> {
constructor(props: IMainCartableProps, state: ICartableState) {
super(props)
this.state = {
status: "Ready",
ISiteCollections: [],
ISPLists:[],
ISPTaskItems:[],
}
}
public _getListOfLists(context: WebPartContext): Promise<ISPLists[]> {
this.state.ISiteCollections.map(async (siteCollection:any)=>{
let url = siteCollection.SPSiteUrl `/forms/_api/web/lists?
$filter=Hidden eq false and BaseTemplate eq 107`;
//console.log(url)
let config: SPHttpClientConfiguration = new
SPHttpClientConfiguration({
defaultODataVersion: ODataVersion.v3})
new Promise<ISPLists[]>( async (resolve, reject)=>{
this.props.context.spHttpClient.get(url, config, { headers: { Accept: "application/json;odata=minimalmetadata;charset=utf-8" }})
.then((response: SPHttpClientResponse) => {
//console.log(response.status)
if(response.status==200){
response.json().then((results: any) => {
//let resultsList = results.PrimaryQueryResult.RelevantResults.Table.Rows;
console.log(results)
results.value.map((result:any)=>{
TaskLists.push({
title: result.Title,
Id:result.Id
})
})
//console.log(TaskLists.length)
//this.setState({ ISPLists:TaskLists })
//console.log(this.state.ISPLists.length)
//resolve(TaskLists);
this.setState({ISPLists:TaskLists})
//this.setState({ ISPLists:TaskLists})
//console.log(this.state.ISPLists[1].title)
//this._getTaskItems()
})
}
// return response.json();
console.log(TaskLists.length)
})
})
})
console.log(TaskLists.length)
console.log("Hereeeee")
this.state.ISPLists.map(SPList=>{
console.log(SPList.title)
})
return
}
CodePudding user response:
There are many things wrong with this code.
- You are using a map method, returning nothing, and adding async operations
this.setStatereplaces the existing state, it doesn't merge your new state with the existing state
Solution:
- If you just need to loop through
ISiteCollectionsand send API requests , then just simply useforEachorforloop to loop through the array - To merge your new state with the existing state, use the es6 spread operator.
this.setState({ispLists:[...this.state.ispLists , ...TaskLists ]})
CodePudding user response:
Im not sure about your problem as Im not working with react for long time but as for debugging this: 1: Make a console.log for the ISPLists just after setState to make sure that the value has been set correctly. 2: Make sure you are looping through it after setState (as I didnt found any async/await in your code).
For cleaner way: make a separate function for setState ISPList value in order to have more flexibility on it and debugging easier. This really could help to debug it.
