Skip to content Skip to sidebar Skip to footer

React - Axios Call Make Too Many Requests

Im learning React & Redux by making a game project. I want to fetch data (attributes) by API, but it cause too many requests. Guess it can be realted to placing axios call dire

Solution 1:

Put the code in a useEffect hook, and then pass in an array as the second parameter to specify what variables should cause it to repeat the effect if they change. An empty array says never to repeat it.

importReact, { useEffect } from'react';

functionAttributes({ attributes, dispatch }) {
  useEffect({
   axios.get(`/api/heroes/1/get-attributes`)
     .then(res => {
       dispatch(AttribAction.set(objectToArray(res.data)));
     });
  }, []);

  // ... etc
}

Solution 2:

You can use a useEffect hook to run the data fetching.

Passing an empty array as the dependencies means the effect will run only once.

importReact, { useEffect } from'react';

functionAttributes({ attributes, dispatch }){

    useEffect(() => {
        axios.get(`/api/heroes/1/get-attributes`)
            .then(res => {
               dispatch(AttribAction.set(objectToArray(res.data)));
            });
    }, [])

    return(
        <divclassName="content">
            {attributes.map((attrib, index) =>
                <divkey={index}className={attrib.id == null ? "attrib-blockempty" : "attrib-block"}><p><strong>{attrib.name}</strong>: {attrib.value}</p><div><buttonclassName="attrib-button"onClick={() => dispatch(AttribAction.increment(attrib.id))}>+</button><buttonclassName="attrib-button"onClick={() => dispatch(AttribAction.decrement(attrib.id))}>-</button></div></div>
            )}
        </div>
    );
}

Post a Comment for "React - Axios Call Make Too Many Requests"