I have been trying to save the result of an API call with a usestate. but I am trying to avoid an interface since the response will be very large and may vary on a case by case basis.
how would I go about saving this response?
const DetailPage = ({navigation, route}) => {
const [recipeData2, setRecipeData2] = useState();
const [loading, setLoading] = useState(true);
const [key, setKey] = useState('APIKEY IS HERE');
const {id} = route.params;
console.log(id)
const getRecipeData2 = async() => {
setLoading(true);
const url = 'https://api.spoonacular.com/recipes/' id '/information?apiKey=' key '&includeNutrition=false';
axios.get(url).then(function (response) {
setRecipeData2(response.data);
console.log(response.data);
console.log(recipeData2);
}).catch(function (error) {
console.log(error);
if(error) {
console.log('error')
}
});
setLoading(false);
}
useEffect(() => {
getRecipeData2();
}, [])
return (
<View>
<Text></Text>
</View>
)
}
CodePudding user response:
What it seems is you need to provide initial value to your useState
and also you are not setting your loader until your promise is completed for that you can use .finally()
block of promise.
So doing these things can fix the issue for you. Here's what needs to be done -
const DetailPage = ({ navigation, route }) => {
const [recipeData2, setRecipeData2] = useState([]);
const [loading, setLoading] = useState(true);
const [key, setKey] = useState('APIKEY IS HERE');
const { id } = route.params;
const getRecipeData2 = async () => {
setLoading(true);
const url = 'https://api.spoonacular.com/recipes/' id '/information?apiKey=' key '&includeNutrition=false';
axios.get(url).then(function (response) {
setRecipeData2(response.data);
}).catch(function (error) {
if (error) console.log('error')
}).finally(function () {
setLoading(false);
})
}
useEffect(() => {
getRecipeData2();
}, [])
return (
<View>
{
recipeData2.map((data, index) => {
return <Text key={ index.toString() }> { data.title } </Text>
})
}
</View>
)
}