Home > OS >  log axios response.data is causing react native app to crash
log axios response.data is causing react native app to crash

Time:04-08

Everything works fine if using a URL that returns JSON e.g https://learn-numbers.herokuapp.com/v2/words/6788/English.
but I am trying to load HTML content from any URL I would had say it was impossible but Axios-hook works fine only that I don't want to make use of it because it crashes the app when requesting redirecting links instead of the error. Instead of error to be caught with status.

Now, are there requesting an Api alternative? that can solve the issue

what is wrong with the code?

import { useState } from 'react';
import axios from 'axios';  

export default () => {
  const [responce, setResponce] = useState({ status: 'Initiated' });

   

  const setLink = async ({ link, search, config }) => {
    setResponce({ status: 'Laoding' });

try {
  const newConfig = config
    ? {
        headers: {
          'User-Agent': '0.21.1',
          Accept: '*/*',
          'Content-Type': 'application/json;charset=utf-8',
        },
        config,
      }
    : {
        headers: {
          'User-Agent': '0.21.1',
          Accept: '*/*',
          'Content-Type': 'application/json;charset=utf-8',
        },
      };

  const res = await axios.get(link, config);
  // console.log('received response:Offline process ');
  if (res) console.log(res.data);
  else console.log('res null');
  setResponce({ status: 'Laoded' , res});
          
} catch (err) {
  console.log('received error: ', err.toJSON());
  setResponce({ status: 'error Net' });
}


};

  return [responce, setLink];
};

After I import the work and use another js file import useUpdateLookup from "./hooks/useLookup"

const [responce,setLink]  = useLookup()

and returns this

<View style={styles.container}>  
     <Button onPress={()=> setLink({link:"https://stackoverflow.com/questions/66830446/how-to-handle-axios-html-response-in-react-native", search:searchOption, config:null})}      
          title="Test URI C" /> 
        <Text style={styles.paragraph}>{JSON.stringify(responce, null, 2)}</Text> 
      </View> 

CodePudding user response:

You are instantiating your state like this

const [responce, setResponce] = useState({ status: 'Initiated'})

And later on in the setlink function setting the state in this manner

setResponce({ status: 'Laoded' , res})

if you want to set the response you are getting from the request in the same state you should add it to the state declaration too .....something like this

 const [responce, setResponce] = useState({ status: 'Initiated', data:{} });

i wouldn't really advise that tho would be better to create a separate state variable for it ...eg

 const [data, `setData`] = useState({});

one other thing to note ..in the axios response the returned data is almost always stored in res.data....'

so setting the state after the request succeeds should look like this

setData(res.data)
  • Related