1axios({
2 method,
3 url,
4 transformResponse: [(data) => {
5 return data
6 }]
7}).then(response => { console.log(response) })
If you’re getting undefined
, there are a few things that you need to keep in mind.
STRING
, you need to parse it to JSON
try .. catch
block so that you catch errors 1async function fetchMovieGenres() {
2 // Get the list of official genres for movies.
3
4 const TMDB_API_TOKEN = ''
5
6 try {
7 let response = await axios({
8 url: `/genre/movie/list`,
9 method: `get`,
10 baseURL: `https://api.themoviedb.org/3`,
11 headers: {
12 Authorization:
13 `Bearer ${TMDB_API_TOKEN}`,
14 },
15 transformResponse: [
16 (response) => {
17 // Do whatever you want to transform the data
18 // e.g. convert the genres array of objects into object of objects
19 // easier to get values by ID that way
20
21 // 1. Use a try catch block to find errors
22 try {
23 console.log(`API Response:`, response)
24 // 2. Response is a STRING. You need to parse it to JSON
25 // One way to identify that right away is interactivity with the response in Console
26 // Objects can be interacted with, can be folded and are color coded. Strings are just gray text
27 console.log(`Response type from API:`, typeof response)
28
29 let parsedResponse
30
31 try {
32 parsedResponse = JSON.parse(response)
33 console.log(`Parsed Response: `, parsedResponse)
34 console.log(`Response type after parsing:`, typeof parsedResponse)
35 } catch (error) {
36 console.error(
37 `There was an error while parsing response data`,
38 error
39 )
40 }
41
42 if (parsedResponse.status === 'success') {
43 return parsedResponse.data
44 } else {
45 console.error(`There was an error while fetching data`)
46 }
47
48 } catch (error) {
49 console.error(
50 `There was an error with Axios transformResponse()`,
51 error
52 )
53 }
54 },
55 ],
56 })
57 return response
58 } catch (error) {
59 console.error(
60 `There was an error when getting movie genres with Axios: \n${error}`
61 )
62 }
63}