Home > Back-end >  Fetch api too many request error in react
Fetch api too many request error in react

Time:07-17

function App(prop) {
    const [content, setContent] = useState([]);
    const [loading , setLoading] = useState(false);
    const fetchUrl = (URl) => {
        fetch(URl)
            .then((res) => {
                return res.json();
            })
            .then((data) => {   
                console.log(data.articles);s
                setContent(data.articles);        
                setLoading(true);
            })
    }
    fetchUrl(prop.link); 

I recon this is causing too many request error when I am trying to use a legit api for fetching data it sends too many requests for some reason and causes 429 error how can i fix that

    return (
        <div className="cards">
            {!loading && <img src={logo}/>}
              {prop.id == 1 && loading &&
    content.map((element)=>{
        if(element.description && element.urlToImage && element.title)
        return <Card image={element.urlToImage} description={element.description.slice(0,150)} title={element.title} key={element.url}/>
    })
  }
              {prop.id == 2 && loading &&
    content.map((element)=>{
        return <Card image={element.url} description={"Eye color is"   element.eye_color   "Hair color is"   element.hair_color   "and is of age"   element.age} title={element.name} key={element.id}/>
    })
  }
  {
   prop.num == 1 && <h1>yo</h1> 
   }
</div>
    );
}

export default App;

CodePudding user response:

You should call fetchUrl from React's useEffect hook. It executes on load first and if any variable in the dependancy array (the second parameter of useEffect) changes. You should change your code as this:

import React, { useEffect } from 'react';
useEffect(()=> {
fetchUrl(prop.link); 
}, [fetchUrl]);

CodePudding user response:

the request should be made once our React component has mounted. To do so, we make our request within the useEffect hook, and we make sure to provide an empty dependencies array as the second argument so that our request is only made once (assuming it's not dependent on any other data in our component like in your case ).

change your App component like this :

useEffect(()=>{
    const fetchUrl = (URl) => {
      fetch(URl)
          .then((res) => {
              return res.json();
          })
          .then((data) => {   
              console.log(data.articles);s
              setContent(data.articles);        
              setLoading(true);
          })
  }
  fetchUrl(prop.link); 

  }, [])

CodePudding user response:

First of all you must never do API requests directly inside your component. If you do, the API request will run every time your component re-renders upon state changes. So obviously, your fetch API runs every time the App component re-renders, and you are updating the state inside your fetch API, which again causes your app to re-render again, runs fetch API again, changes state again, app re-renders and hence the too many requests error.

So where should you put the API request logic? Inside useEffect(callback, dependencies) hook. With this hook you can actually control how many times or when you want the API request to run after initial rendering based on your dependencies argument.

useEffect(callback) : Runs after EVERY rendering.
useEffect(callback,[]): Runs ONCE after initial rendering.
useEffect(callback,[state, prop]): Runs ONCE after initial rendering and after every rendering ONLY if state or prop changes.

As you can see below, you have an empty array dependency and hence your request will run only ONCE after initial rendering. If you want to run it again after state or prop change, then you can add those state or prop as dependency.

useEffect(() => {
  const fetchUrl = (URl) => {
    fetch(URl)
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        console.log(data.articles);
        s
        setContent(data.articles);
        setLoading(true);
      })
  }
  fetchUrl(prop.link);
}, []);

  • Related