How do I use a setTimeout to limit the time in a fetch request? [duplicate]











up vote
0
down vote

favorite













This question already has an answer here:




  • Fetch API request timeout?

    6 answers




I'm working on a React game search app that pulls API data from a third-party source. When the user searches an input that can't be found, the fetch just hangs there without stopping. Basically what I'm stuck on figuring out how to cancel the fetch request onces a setTimeout if finished after say, 10 seconds. If no response is received by then I want it to be canceled and render an error message. Thanks for your help in advance!



class Search extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
games: ,
error: false,
loading: false
}
}

updateInput = (event) => {
this.setState({
title: event.target.value
});
}

handleGames = (search) => {
const proxyUrl = `https://cors-anywhere.herokuapp.com/`;
const key = `8cd10a7136710c1003c8e216d85941ace5a1f00e`;
const endpoint = `https://www.giantbomb.com/api/search/?api_key=`;
const url = `${proxyUrl}${endpoint}${key}&format=json&resources=game&query=${search}&limit=30`;

this.setState({ loading: true }, () => {

fetch(url)
.then(res => res.json())
.then(data => {
const response = data.results;

response.forEach(game => {
this.setState(prevState => ({
games: prevState.games.concat(game),
loading: false
}))
});
}).catch(error => {
console.log('Request failed', error);
});

this.setState({
games:
})
})

}

handleSubmit = (e) => {
const { title } = this.state;
e.preventDefault();

if (!title) {
this.setState({ error: true })
} else {
this.setState({ error: false })
this.handleGames(title);
}
}

render() {
const { games, error, loading } = this.state;
return (
<div className="App">
<div className="search-bar">
<form>
<input
className="input-field"
type="text"
placeholder="Search Game"
onChange={this.updateInput}
/>
<button
className="search-button"
onClick={this.handleSubmit}
>Search</button>
</form>
<span className="error">{error ? "You kind of need to type something first, genius." : ""}</span>
</div>
<div className="games-container">
{loading ? (
<div className="loading-div">
<i className="fa fa-3x fa-spinner fa-spin" />
<p className="loading">Loading....</p>
</div>
) : (
games.map(game => {
return <Game
key={game.id}
game={game}
icon={game.image.icon_url}
gameTitle={game.name}
/>
})
)

}
</div>
</div>

);
}
}









share|improve this question













marked as duplicate by Jonas Wilms javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 2




    fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
    – estus
    2 days ago















up vote
0
down vote

favorite













This question already has an answer here:




  • Fetch API request timeout?

    6 answers




I'm working on a React game search app that pulls API data from a third-party source. When the user searches an input that can't be found, the fetch just hangs there without stopping. Basically what I'm stuck on figuring out how to cancel the fetch request onces a setTimeout if finished after say, 10 seconds. If no response is received by then I want it to be canceled and render an error message. Thanks for your help in advance!



class Search extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
games: ,
error: false,
loading: false
}
}

updateInput = (event) => {
this.setState({
title: event.target.value
});
}

handleGames = (search) => {
const proxyUrl = `https://cors-anywhere.herokuapp.com/`;
const key = `8cd10a7136710c1003c8e216d85941ace5a1f00e`;
const endpoint = `https://www.giantbomb.com/api/search/?api_key=`;
const url = `${proxyUrl}${endpoint}${key}&format=json&resources=game&query=${search}&limit=30`;

this.setState({ loading: true }, () => {

fetch(url)
.then(res => res.json())
.then(data => {
const response = data.results;

response.forEach(game => {
this.setState(prevState => ({
games: prevState.games.concat(game),
loading: false
}))
});
}).catch(error => {
console.log('Request failed', error);
});

this.setState({
games:
})
})

}

handleSubmit = (e) => {
const { title } = this.state;
e.preventDefault();

if (!title) {
this.setState({ error: true })
} else {
this.setState({ error: false })
this.handleGames(title);
}
}

render() {
const { games, error, loading } = this.state;
return (
<div className="App">
<div className="search-bar">
<form>
<input
className="input-field"
type="text"
placeholder="Search Game"
onChange={this.updateInput}
/>
<button
className="search-button"
onClick={this.handleSubmit}
>Search</button>
</form>
<span className="error">{error ? "You kind of need to type something first, genius." : ""}</span>
</div>
<div className="games-container">
{loading ? (
<div className="loading-div">
<i className="fa fa-3x fa-spinner fa-spin" />
<p className="loading">Loading....</p>
</div>
) : (
games.map(game => {
return <Game
key={game.id}
game={game}
icon={game.image.icon_url}
gameTitle={game.name}
/>
})
)

}
</div>
</div>

);
}
}









share|improve this question













marked as duplicate by Jonas Wilms javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 2




    fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
    – estus
    2 days ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite












This question already has an answer here:




  • Fetch API request timeout?

    6 answers




I'm working on a React game search app that pulls API data from a third-party source. When the user searches an input that can't be found, the fetch just hangs there without stopping. Basically what I'm stuck on figuring out how to cancel the fetch request onces a setTimeout if finished after say, 10 seconds. If no response is received by then I want it to be canceled and render an error message. Thanks for your help in advance!



class Search extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
games: ,
error: false,
loading: false
}
}

updateInput = (event) => {
this.setState({
title: event.target.value
});
}

handleGames = (search) => {
const proxyUrl = `https://cors-anywhere.herokuapp.com/`;
const key = `8cd10a7136710c1003c8e216d85941ace5a1f00e`;
const endpoint = `https://www.giantbomb.com/api/search/?api_key=`;
const url = `${proxyUrl}${endpoint}${key}&format=json&resources=game&query=${search}&limit=30`;

this.setState({ loading: true }, () => {

fetch(url)
.then(res => res.json())
.then(data => {
const response = data.results;

response.forEach(game => {
this.setState(prevState => ({
games: prevState.games.concat(game),
loading: false
}))
});
}).catch(error => {
console.log('Request failed', error);
});

this.setState({
games:
})
})

}

handleSubmit = (e) => {
const { title } = this.state;
e.preventDefault();

if (!title) {
this.setState({ error: true })
} else {
this.setState({ error: false })
this.handleGames(title);
}
}

render() {
const { games, error, loading } = this.state;
return (
<div className="App">
<div className="search-bar">
<form>
<input
className="input-field"
type="text"
placeholder="Search Game"
onChange={this.updateInput}
/>
<button
className="search-button"
onClick={this.handleSubmit}
>Search</button>
</form>
<span className="error">{error ? "You kind of need to type something first, genius." : ""}</span>
</div>
<div className="games-container">
{loading ? (
<div className="loading-div">
<i className="fa fa-3x fa-spinner fa-spin" />
<p className="loading">Loading....</p>
</div>
) : (
games.map(game => {
return <Game
key={game.id}
game={game}
icon={game.image.icon_url}
gameTitle={game.name}
/>
})
)

}
</div>
</div>

);
}
}









share|improve this question














This question already has an answer here:




  • Fetch API request timeout?

    6 answers




I'm working on a React game search app that pulls API data from a third-party source. When the user searches an input that can't be found, the fetch just hangs there without stopping. Basically what I'm stuck on figuring out how to cancel the fetch request onces a setTimeout if finished after say, 10 seconds. If no response is received by then I want it to be canceled and render an error message. Thanks for your help in advance!



class Search extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
games: ,
error: false,
loading: false
}
}

updateInput = (event) => {
this.setState({
title: event.target.value
});
}

handleGames = (search) => {
const proxyUrl = `https://cors-anywhere.herokuapp.com/`;
const key = `8cd10a7136710c1003c8e216d85941ace5a1f00e`;
const endpoint = `https://www.giantbomb.com/api/search/?api_key=`;
const url = `${proxyUrl}${endpoint}${key}&format=json&resources=game&query=${search}&limit=30`;

this.setState({ loading: true }, () => {

fetch(url)
.then(res => res.json())
.then(data => {
const response = data.results;

response.forEach(game => {
this.setState(prevState => ({
games: prevState.games.concat(game),
loading: false
}))
});
}).catch(error => {
console.log('Request failed', error);
});

this.setState({
games:
})
})

}

handleSubmit = (e) => {
const { title } = this.state;
e.preventDefault();

if (!title) {
this.setState({ error: true })
} else {
this.setState({ error: false })
this.handleGames(title);
}
}

render() {
const { games, error, loading } = this.state;
return (
<div className="App">
<div className="search-bar">
<form>
<input
className="input-field"
type="text"
placeholder="Search Game"
onChange={this.updateInput}
/>
<button
className="search-button"
onClick={this.handleSubmit}
>Search</button>
</form>
<span className="error">{error ? "You kind of need to type something first, genius." : ""}</span>
</div>
<div className="games-container">
{loading ? (
<div className="loading-div">
<i className="fa fa-3x fa-spinner fa-spin" />
<p className="loading">Loading....</p>
</div>
) : (
games.map(game => {
return <Game
key={game.id}
game={game}
icon={game.image.icon_url}
gameTitle={game.name}
/>
})
)

}
</div>
</div>

);
}
}




This question already has an answer here:




  • Fetch API request timeout?

    6 answers








javascript reactjs






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









envincebal

397




397




marked as duplicate by Jonas Wilms javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Jonas Wilms javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 2




    fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
    – estus
    2 days ago














  • 2




    fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
    – estus
    2 days ago








2




2




fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
– estus
2 days ago




fetch isn't cancellable. This is one of reasons to not use it. You can reject a promise on timeout but a request itself won't be aborted.
– estus
2 days ago












1 Answer
1






active

oldest

votes

















up vote
0
down vote













Instead of directly using fetch you can nest it inside a Promise. You will find a lot of implementation doing a search. That's one I used.



const advFetch = (url, ...) => {
const TIMEOUT = 10000;
let didTimeOut = false;

return new Promise(function(resolve, reject) {
const timeout = setTimeout(() => {
didTimeOut = true;
reject(new Error('Request timed out'));
}, TIMEOUT);

fetch(url, ...).then(function(response) {
clearTimeout(timeout);
if (!didTimeOut) {
resolve(response);
}
})
.catch(function(err) {
if (didTimeOut) {
return;
}
reject(err);
});
})
}


Note: the fetch isn't really cancelled (this is not possible), it will continue until network timeout is reached, but it will be ignored by your application.






share|improve this answer




























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Instead of directly using fetch you can nest it inside a Promise. You will find a lot of implementation doing a search. That's one I used.



    const advFetch = (url, ...) => {
    const TIMEOUT = 10000;
    let didTimeOut = false;

    return new Promise(function(resolve, reject) {
    const timeout = setTimeout(() => {
    didTimeOut = true;
    reject(new Error('Request timed out'));
    }, TIMEOUT);

    fetch(url, ...).then(function(response) {
    clearTimeout(timeout);
    if (!didTimeOut) {
    resolve(response);
    }
    })
    .catch(function(err) {
    if (didTimeOut) {
    return;
    }
    reject(err);
    });
    })
    }


    Note: the fetch isn't really cancelled (this is not possible), it will continue until network timeout is reached, but it will be ignored by your application.






    share|improve this answer

























      up vote
      0
      down vote













      Instead of directly using fetch you can nest it inside a Promise. You will find a lot of implementation doing a search. That's one I used.



      const advFetch = (url, ...) => {
      const TIMEOUT = 10000;
      let didTimeOut = false;

      return new Promise(function(resolve, reject) {
      const timeout = setTimeout(() => {
      didTimeOut = true;
      reject(new Error('Request timed out'));
      }, TIMEOUT);

      fetch(url, ...).then(function(response) {
      clearTimeout(timeout);
      if (!didTimeOut) {
      resolve(response);
      }
      })
      .catch(function(err) {
      if (didTimeOut) {
      return;
      }
      reject(err);
      });
      })
      }


      Note: the fetch isn't really cancelled (this is not possible), it will continue until network timeout is reached, but it will be ignored by your application.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Instead of directly using fetch you can nest it inside a Promise. You will find a lot of implementation doing a search. That's one I used.



        const advFetch = (url, ...) => {
        const TIMEOUT = 10000;
        let didTimeOut = false;

        return new Promise(function(resolve, reject) {
        const timeout = setTimeout(() => {
        didTimeOut = true;
        reject(new Error('Request timed out'));
        }, TIMEOUT);

        fetch(url, ...).then(function(response) {
        clearTimeout(timeout);
        if (!didTimeOut) {
        resolve(response);
        }
        })
        .catch(function(err) {
        if (didTimeOut) {
        return;
        }
        reject(err);
        });
        })
        }


        Note: the fetch isn't really cancelled (this is not possible), it will continue until network timeout is reached, but it will be ignored by your application.






        share|improve this answer












        Instead of directly using fetch you can nest it inside a Promise. You will find a lot of implementation doing a search. That's one I used.



        const advFetch = (url, ...) => {
        const TIMEOUT = 10000;
        let didTimeOut = false;

        return new Promise(function(resolve, reject) {
        const timeout = setTimeout(() => {
        didTimeOut = true;
        reject(new Error('Request timed out'));
        }, TIMEOUT);

        fetch(url, ...).then(function(response) {
        clearTimeout(timeout);
        if (!didTimeOut) {
        resolve(response);
        }
        })
        .catch(function(err) {
        if (didTimeOut) {
        return;
        }
        reject(err);
        });
        })
        }


        Note: the fetch isn't really cancelled (this is not possible), it will continue until network timeout is reached, but it will be ignored by your application.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        Luca Fabbri

        5,414930




        5,414930















            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga