Afsanefda
Afsanefda

Reputation: 3339

React set-state doesn't update in fetch success function (on key up event)

I have a search component containing an input on which I defined a key up event handler function for fetching data based on entered string. As you can see below:

class SearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            timeout: 0,
            query: "",
            response: "",
            error: ""
        }
        this.doneTypingSearch = this.doneTypingSearch.bind(this);
    }
    doneTypingSearch(evt){
        var query = evt.target.value; 
        if(this.state.timeout) clearTimeout(this.state.timeout);
        this.state.timeout = setTimeout(() => {
            fetch('https://jsonplaceholder.typicode.com/todos/1/?name=query' , {
                method: "GET"
            })
            .then( response => response.json() )
            .then(function(json) {
                console.log(json,"successss") 
                //Object { userId: 1, id: 1, title: "delectus aut autem", completed: false }  successss

                this.setState({
                    query: query,
                    response: json
                })
                console.log(this.state.query , "statesssAfter" )
            }.bind(this))
            .catch(function(error){
                this.setState({
                    error: error
                })
            });
        }, 1000);
    }
  render() {
    return (
        <div>
            <input type="text" onKeyUp={evt => this.doneTypingSearch(evt)} />        
            <InstantSearchResult data={this.state.response} /> 
        </div>
        );
    }
}
export default SearchBox;

The problem is the setState which I used in the second .then(). The response won't update . I want to update it and pass it to the InstantSearchResult component which is imported here. Do you have any idea where the problem is ?

Edit - Add InstantSearchResult component

class InstantSearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            magicData: ""
        }
    }
    // Both methods tried but got error =>  Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    componentDidUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    shouldComponentUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    render() {
        return (
            <h1>{ this.state.magicData}</h1>
        );
    }
}
export default InstantSearchBox;

Upvotes: 3

Views: 4206

Answers (2)

Afsanefda
Afsanefda

Reputation: 3339

Edit:

Be aware that setState is asynchronous reading this article.

I've understand that the setState works fine in my fetch success the problem was the console.log which I shouldn't use it after setState instead I console.log in render() and I found out that the state updates correctly .

The other thing I wasn't careful for was the InstantSearchResult Constructor! When I re-render the SearchBox component consequently the InstantSearchResult renders each time but it's constructor runs just once. And if I use setState in InstantSearchResult I will face an infinite loop so I have to use this.props instead to pass the data to the second component.

Upvotes: 3

Kubwimana Adrien
Kubwimana Adrien

Reputation: 2531

this has been overridden inside the promise callback function. You to save it to a variable:

doneTypingSearch(evt){
        var _this = this,
            query = evt.target.value; 
        if(this.state.timeout) clearTimeout(this.state.timeout);
        this.state.timeout = setTimeout(() => {
            fetch('https://jsonplaceholder.typicode.com/todos/1/?name=query' , {
                method: "GET"
            })
            .then( response => response.json() )
            .then(function(json) {
                console.log(json,"successss") 
                //Object { userId: 1, id: 1, title: "delectus aut autem", completed: false }  successss

                _this.setState({
                    query: query,
                    response: json
                })
                console.log(_this.state.query , "statesssAfter" )
            }/*.bind(this)*/)
            .catch(function(error){
                _this.setState({
                    error: error
                })
            });
        }, 1000);
    }

Upvotes: 2

Related Questions