javascriptreact-native

Invalid hook call in react native


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


Solution

  • 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.