skip to Main Content

im tring to call this hook but im receiving this error

Possible Unhandled Promise Rejection (id: 6):
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

this is my code:

const handleEvento = async (dayy) => {
  useEffect(()=>{
    axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`)
         .then(response =>{
           //Ordenar os dados pelo id em ordem crescente
           const sortData= response.data.sort((a,b) => a.id - b.id);

    
           setData2(sortData);

           console.log(data2)
      
         })
       .catch(error => {
         console.log(JSON.stringify(error));
        });
  },[]);
}




onDayPress={day => {
    handleEvento(day.dateString)        
}}

i really dont know what im missing here if soomeone can helps i would be really glad

2

Answers


  1. React hooks rely on the order of calling, so there are some rules how to use them. It’s described in the Using Hooks part of the documentation. In short: you can’t use hooks like you did, because it makes the call order unpredictable.

    In your case, it looks like useEffect() is used incorrectly also from the logical perspective. You can just skip it entirely:

    const handleEvento = async (dayy) => {
      try {
        const response = await axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`);
    
        //Ordenar os dados pelo id em ordem crescente
        const sortData = response.data.sort((a, b) => a.id - b.id);
    
        setData2(sortData);
    
        console.log(data2);
      } catch (error) {
        console.log(JSON.stringify(error));
      }
    };
    

    Notice how I also simplified your code by using await.

    One more note – your console.log(data2) will not log the latest value, because setData2() only queues state for updating. It’s going to be effectively changed at the end of the current cycle.

    Login or Signup to reply.
  2.   You have used async without an await functionality. Please check and make changes accordingly. Since the useEffect hook cannot be used inside another function, use the function inside useEffect as below.
    Note: Hooks cannot be used as callbacks directly inside any other function.
    useEffect(()=>{
    handleEvento()
    },[])
    
    const handleEvento = async (dayy)=>{
    try{
     const result = await axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`)
      result.then(response =>{
               //Ordenar os dados pelo id em ordem crescente
               const sortData= response.data.sort((a,b) => a.id - b.id);
    
        
               setData2(sortData);
    
               console.log(data2)
          
             })
           
    }
    .catch(error => {
             console.log(JSON.stringify(error));
            });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search