title: how to set axios timeout
body: <p>New to javascript/react/node/axios. Not new to programming</p>
  <p>Having issues trying to get timeout on axios working in a mobile react app.</p>
  <p>I have a node server with API end point set to test; this will accept the request, throw an error and simply not respond.</p>
  <p>Eg: throw new Error(“testing for timeout”)</p>
  <p>The app is hanging and will not move on until I stop the node server where immediately the catch block is executed.</p>
  <p>I can verify that the app made contact with server by having the server do a console.log(&quot;hello&quot;) before throwing the error</p>
  <p>I’ve created a new react app by new folder, “react-native init”, creating a button on app.js to initiate the call. Relevant code:</p>
  <pre><code>const axios = require('axios')
  
  const test1Press = async () =&gt; {
  
    console.log(&quot;test1 pressed&quot;)
  
    // obviously not the actual url in this stackoverflow post
    axios.defaults.baseURL = 'https://mynodeserver.com/api'
  
    console.log(&quot;pre call&quot;)
  
    try
    {
      await axios.post('/debug/throw', {timeout: 2000})
      console.log(&quot;post call passed&quot;)
    }
    catch (err)
    {
      console.log(&quot;post call failed&quot;)
    }
  }
  </code></pre>
  <p>Console window shows Pre call; then hangs. When I stop node server the app logs immediately with &quot;post call failed&quot;</p>
  <p>I have also tried:</p>
  <pre><code>axios.defaults.timeout = 2000
  </code></pre>
  <p>and using an axios instance like:</p>
  <pre><code>axinst = axios.create({
    baseURL: 'https://parcelscan-staging.ctilogistics.com/api',
    timeout: 2000
  })
  
  console.log(&quot;pre call&quot;)
  
  try
  {
    await axinst.post('/debug/throw')
    console.log(&quot;post call passed&quot;)
  }
  catch (err)
  {
    console.log(&quot;post call failed&quot;)
  }
  </code></pre>
  <p>I can’t see what I’m doing wrong.</p>
  <p>EDIT:</p>
  <p>On further research I found forum posts with similar issues; looks like axios timeout may not be reliable as of May 2020; and a year later now in June 2021 ?</p>
  <p>Suggested solutions are canceltokens eg:</p>
  <pre><code>const source = CancelToken.source();
  try {
      let response = null;
      setTimeout(() =&gt; {
          if (response === null) {
              source.cancel();
          }
      }, 2000);
          
      response = await axios.post('/url',null,
          {cancelToken: source.token});
      // success
  } catch (error) {
  // fail
  }
  </code></pre>
  <p>Tested this and working</p>