I'm trying to fetch a response from pexels api for pictures and what I'm trying to do is populate the empty array of defaultImages of the photos object I get from the response.
import * as React from "react";
import { ChakraProvider} from "@chakra-ui/provider";
import {theme} from "@chakra-ui/theme";
import {Text,Box} from "@chakra-ui/react";
import axios from 'axios';
const App = () => {
return (
<ChakraProvider theme={theme}>
<Box>
<Display/>
</Box>
</ChakraProvider>
);
}
export default App;
interface Image {
id:number,
width:number,
height:number,
avg_color:string,
liked:boolean,
photographer:string,
photographer_id:number,
photographer_url:string,
src:object,
}
const defaultImages : Image[] = [];
function Display() {
const [Images,setImages] : [Image[], (images: Image[]) => void] = React.useState(defaultImages);
const [loading,isLoading] : [boolean,(loading: boolean) => void] = React.useState<boolean>(true);
const [error,setError] : [string,(error: string) => void] = React.useState("");
React.useEffect(() => {
axios.get<Image[]>('https://api.pexels.com/v1/curated?page=2&per_page=40', {
headers: {
Authorization : '563492ad6f91700***********************************'
},
}).then(response => {
setImages(response.data.photos);
isLoading(false);
console.log("it worked!",response.data.photos);
}).catch(ex => {
const error = ex.response.status === 404 ? 'Page not found':'Something wrong has happened';
setError(error);
isLoading(false);
console.log(error);
})
},[]);
return (
<Text></Text>
);
}
I get the response data just fine, and the array of objects displays on the console when I add '.photos' accessor after (response.data), but I'm getting an error Uncaught (in promise) TypeError: ex.response is undefined.
I don't understand what's the problem here. I tried adding a 'photos' array property explicitly on Image interface but I still get the same error.
The Uncaught (in promise) TypeError: ex.response is undefined Error just tells you that the ex object has no response field defined. It has nothing to do with your photos array, which is correctly implemented.
This is the result of you trying to access the response of your request, which is currently not present. This can happen for example, if the request was made, but no response was recieved from the server.
To make sure to only check the error code of the response if it's present, wrap your code in an if statement to check if the response is set.
Try this:
}).catch(ex => {
if(ex.response) {
const error = ex.response.status === 404 ? 'Page not found':'Something wrong has happened';
setError(error);
isLoading(false);
console.log(error);
}
})
You can find more examples of error handling in the axios documentation.
Little bonus pro tip from me: Calling your variable error instead of ex and renaming error to errorMessage makes your code easier to read and understand.