简体   繁体   中英

setState not setting state variable React

I'm trying to set state variable to response data from api call but unable to do so . I have division array in responseJson which i'm trying to set to divisions array in state. I'm getting the responseJson values on console.log but when i'm trying setState({...this.state,divisions:responseJson.division}) i'm not getting any data on console.

state

    this.state={
    token: data.token,
    role: data.role,
    userId: data.userId,
    organizationId: data.organizationId,
    organizationName: data.organization_name,
    workspacePP: false,
    workspaces: [],
    divisions:[],
    addWorkspace: null,
    isDivisionViewable:false,
    divisionName:null

};

function addDivision

 addDivision=()=> {

 const uri = `${APPURL}/workspace/division/create`;
 console.log('dddddd',this.state)
  fetch(uri, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${this.state.token}`
    },
    body: JSON.stringify({
              workspace_id: this.state.workspaces[0].workspace_id,
              organization_id: this.state.organizationId,
              division:this.state.divisionName
        }),
    }).then((res)=>res.json()).then(responseJson=>{

          if(!responseJson.status){
            message.error(responseJson.error);
            return;
          }
          console.log('dddd',responseJson);

          this.setState({...this.state,divisions:responseJson.division})

    })
    console.log(this.state)//returns empty array
  }

responseJson

{status: true, division: Array(1), created_at: {…}, user: {…}}
created_at:
updated_at: ["2019-03-09 14:05:26"]
__proto__: Object
division: Array(1)
0: {id: 5, userid: "t863060h", workspace_id: "ROPHV6W", workspace_name: 
"workspace", created_at: "2019-03-09 13:39:31", …}
length: 1
__proto__: Array(0)
status: true
user:
created_at: "2019-03-08 18:29:56"
email: "trycatchh@mail.com"
email_verification: 1
id: 1
loginStatus: 0
mobile_otp: 0
mobile_verification: 0
phone: "9632587410"
role: "Admin"
slug: ""
status: 2
team: null
uid: null

updated_at: "2019-03-08 18:29:56" userid: "t863060h" username: "tryy catchh"

console.log(this.state)

nName: "tryCatchh", …}
addWorkspace: true
divisionName: "dud"
**divisions**: Array(0)//no data
length: 0
__proto__: Array(0)
isDivisionViewable: true
organizationId: "finalids"
organizationName: "tryCatchh"
role: "Admin"
userId: "t863060h"
workspacePP: false
workspaces: [{…}]

other funtction

  showDivision=()=>{
        console.log('dddd',this.state.divisions);
  }

SetState is asynchronous so To see updated state value you need to

Change

this.setState({...this.state,divisions:responseJson.division})

To

  this.setState({
       divisions:responseJson.division
  }, () => {
        console.log(this.state.divisions);//here you will get updated divisions state value
   });

Notice your setState is in then function, and will run after the API call response. Your console.log(this.state) will run immediately after calling the API.

if you want to see the final state after the API call, pass a callback func as the second parameter to setState like this:

this.setState({ divisions:responseJson.division }, () => console.log(this.state))

note: you don't need to destructure the state when calling setState, React does it for you already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM