1

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: "[email protected]"
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);
  }

2 Answers 2

3

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
   });
Sign up to request clarification or add additional context in comments.

4 Comments

@Hemadari Dasari Thanks for the answer it works for me now
@Hemadari Dasari i tried to use this divisions variable in other function by this.state.divisions but it returned null.
It won’t be able in other functions until the component is rendered
@ Hemadri Dasar I have edited the post can you check once
2

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.

5 Comments

thanks for the answer ... now i tried to use this divisions variable in other function by this.state.divisions but it returned null
the problem is when you use it. can you share the code?
@Mike3096 when do you call showDivision? it will be the same if you call that function immediately after api call, the response isn't there yet. and what is your use case
my case is i have to use divisions in render function
render function should be re-run when the state change, and will have the latest data. if it's still not working can you create a sample in codesandbox I can have a look

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.