Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda