skip to Main Content

I making CORS request in my react app which is allowed from the server.

When I am making an API call from UseEffect with [] its retuning CROS error but when calling the same API on button click its working fine or with setTimeOut inside useEffect its working fine.

I am not able understand why.

function getData(){
  axios.post('/cors_enabled_api_URL',body).then(res=>{
        console.log(res);
    }).catch(err=>{
        console.log(err);
    });
}


export default function DashBoard(){      
    const {data,setData} = useState(null)
    useEffect(()=>{           
      getData();          // API is not working and returning CORS
    },[])
    return (                
         <h1>DashBoard</h1>
        <button onClick={getData}>Test</button> // API call is Working
    )
}

2

Answers


  1. Try using setTimeout inside useEffect.

    When you make the API call immediately within the useEffect with an empty dependency array, the request might be fired before the necessary CORS headers are set. This can happen if the required headers are added dynamically by the server only after the initial page load.

    Login or Signup to reply.
  2. Try adding async to your getData function :

    async function getData(){
      axios.post('/cors_enabled_api_URL',body).then(res=>{
            console.log(res);
        }).catch(err=>{
            console.log(err);
        });
    }
    
    
    export default function DashBoard(){      
        const {data,setData} = useState(null)
        useEffect(()=>{           
          getData();          // API is not working and returning CORS
        },[])
        return (                
             <h1>DashBoard</h1>
            <button onClick={getData}>Test</button> // API call is Working
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search