Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
Losing state value after function is finished

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 
   
  }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There are many things wrong with this code.

  1. You are using a map method, returning nothing, and adding async operations
  2. this.setState replaces the existing state, it doesn't merge your new state with the existing state

Solution:

  1. If you just need to loop through ISiteCollections and send API requests , then just simply use forEach or for loop to loop through the array
  2. To merge your new state with the existing state, use the es6 spread operator.this.setState({ispLists:[...this.state.ispLists , ...TaskLists ]})
about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda