Home > OS >  Having an infinite loop on data rest api, react
Having an infinite loop on data rest api, react

Time:11-16

Im learning react and im trying to make a call for the poke api but im having infinite loop I really dont know what im doing. heres my app

useAxios.ts

import axios from 'axios';
import { useState, useEffect } from 'react';
import Request from '../interfaces/request';

const useAxios = (request: Request) => {
    const client = axios.create({
        baseURL: "https://pokeapi.co/api/v2" 
     });
    const [response, setResponse] = useState(null);
    const [error, setError] = useState('');
    const fetchData = async () => {
        const response = await client[request.method](request.url,request.body) 
        if(response.status <= 399){
            setResponse(response.data);
        }
        else{
            setError(response.statusText);
        }
    };
    useEffect(() => {
        fetchData();
    }, [request]);
    return { response, error };
};
export default useAxios;

heres the view

import Pokecard from "../components/pokecard/Pokecard";
import { Methods } from "../interfaces/request";
import axios from '../plugins/Useaxios';

function App2() {
  const response = axios({
    url: '/pokemon/ditto',
    method: Methods['get'],
    body: JSON.stringify({}),
    headers: JSON.stringify({})
  })
  console.log(response)
  return (
    <>
      <Pokecard />;
    </>
  );
}

export default App2;

I tried to use an useEffect but no results o i dont know if im doing it wrong

CodePudding user response:

You should remove the request from the dependency array since this causes the infinite loop. When fetchData sets a new state, error or response it will trigger a re-render in the App2 component which will trigger the useAxios etc...

useEffect(() => {
  fetchData();
}, []);
  • Related