how to make api response not be the same as previous result in React JS

Viewed 122

I am using an Free API of Advice Slip and when I am fetching data from API on Button click some time it gives me the same result from API Response how can I manage to filter that if the API response is same as previous so call the API again. you can check the code below.

 getAdvice = async () => {
    this.setState({ advice: "", load: true });
    await fetch("https://api.adviceslip.com/advice")
    .then((response) => response.json())
    .then((data) => {
    this.setState({ advice: data.slip.advice, load: false })});
    };
2 Answers

You need to check the returned value from API and if different, set it as new state value, or fetch again.

I used an approach with hooks but the code should be similar with setState

  const getAdvice = async () => {
    setLoading(true);
    setAdvice("");
    await fetch("https://api.adviceslip.com/advice")
      .then((response) => response.json())
      .then((data) => {
        if (advice === data.slip.advice) {
          getAdvice();
        } else {
          setAdvice(data.slip.advice);
          setLoading(false);
        }
      });
  };

sandbox

Can be like this:

getAdvice = async () => {
  this.setState({ load: true });
  await fetch("https://api.adviceslip.com/advice")
  .then((response) => response.json())
  .then((data) => {
     if (data.slip.advice === this.state.advice) {
       this.getAdvice();
     } else {
        this.setState({ advice: data.slip.advice, load: false)} 
     }
   });
}

If result is the same we recursively call same function, if not we update state.

Related