0

Below is the initial state which is assigned

state = {
            movie : null,
            actors : null,
            directors : [],
            loading : false
        }

Below is the set state which i set and at the end to set state as put in comment when it is set and not set. I'm not able to access the this.state outside.

this.setState({movie:result},() => {
                      //then fetch the actors
                      const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
                      fetch(endpoint)
                      .then(result => result.json())
                      .then(result=>{
                        const directors =result.crew.filter((member)=> member.job==='Director' ); 
                        this.setState({
                            actors : result.cast,
                            directors,
                            loading : false
                        })
                       console.log(this.state); //here value is coming
                      })         
                  })console.log(this.state); //here value is not coming

How to get this.state value with updated info?


render() { 
    //removed code below mull div
    return  ( 
    <div className="rmdb-movie">
        {this.state.movie ? 
        <div>
          <Navigation movie={this.props.location.movieName}/>
        </div>  
         : null
        }

    </div> 
    )
}

5 Answers 5

2

What you're experiencing is the result of using asynchronous functions. The callback you pass to this.setState() is called whenever the state is set, and there might be a delay between when you call this.setState() and when the state is actually updated. This means that the callback may or may not be executed when you reach the second console.log().

This explains why you are seeing these results. The first console.log() is actually called after the second console.log.

Sign up to request clarification or add additional context in comments.

7 Comments

I undestood your comments, but wat to do to get update this.state value
It depends. Why do you want to access the updated values?
this is because state is having movie,actors, directors as null. So after calling API i need updated values
Ok then you want to access this.state inside of the callback function (i.e. where you are using your first console.log())
actually i want to use in render function, but console.log(this.state) params is null
|
1

This is react lifecycle ! The setState function is not executed instantaneously. The inner console.log prints the good values because in the callback of setState you are sur it is executed. The outer console.log is executed before setState has actually modified the state and so you don't see the updated info.

1 Comment

then how to fix this, i mean how can i get updated this.state with values
1

What you are seeing is actually what is expected, this is because Javascript in general and your specific fetch API call is asynchronous. Your first console.log() is inside the response from the fetch request, so it is only executed when the server returns the response(which could be a few seconds or more), then the state is set, then you print using console.log. The second console.log is outside, and will actually print instantly ,even before the async API call is made, before the state has actually been updated. Therefore, I would recommend that whatever action you want to do after the state is set, should be done where the first console.log is. Or preferably like this in a callback that you can pass to this.setState to ensure the state has been updated.

this.setState({movie:result},() => {
                      //then fetch the actors
                      const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
                      fetch(endpoint)
                      .then(result => result.json())
                      .then(result=>{
                        const directors =result.crew.filter((member)=> member.job==='Director' ); 
                        this.setState({
                            actors : result.cast,
                            directors,
                            loading : false
                        },()=>{
                        // API Call has returned and state has been updated
                        // Now access this.state 
                        });
                      })         
                  })

Comments

0

setState operation is asynchronous, you can read more about it in react documentation.

What problem are you trying to solve? Probably you need to use hook componentDidUpdate or just use this value in next render call.

3 Comments

I am trying to achieve to get updated this.state with updated params
What business problem are you solving? Do you need to render view with updated data or show popup?
React will call render function after setState, so just check for data in render function like if (this.state.data) return <SomeComponent data={this.state.data}>
0

I think you should rethink the code because there is no way result will get to movies the way you put it. Except somehow you update another state inside the API function to fetch movies. So somehow you can call fetch which you must have binded to your class this.fetch = this.fetch.bind(this) from some onclick or onchange or something.

fetch =() =>{

        const endpoint= `${API_URL}movie/${this.props.match.params.movieId}/credits?api_key=${API_KEY}`;
        fetch(endpoint)
        .then(result => result.json())
        .then(result=>{
          const directors =result.crew.filter((member)=> member.job==='Director' ); 
          this.setState({
              actors : result.cast,
              directors,
              loading : false,
              movies:result
          })


        }) 

  }

Comments

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.