Unable to access fetched data from Flickr API using axios in React.js

95 Views Asked by At
import React from "react";
import axios from "axios";

function API(props) {
    axios
    .get("https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=8a67ea6102e401ad62ded664a49689ec&text=cat&per_page=5&size=w&format=json")
    .then((response) => {
        console.log(response.data. ???)
    });
    return true;
}

export default API;

When I only do console.log(response.data), I do get the data as console.log(response.data)

But when I try to access anything inside it like console.log(response.data.photos), then it returns undefined in the console

I want to access the data inside this response.data

1

There are 1 best solutions below

0
Jay F. On

Flicker returns a string wich is wrapped with a function not a json. You can call the function using eval().

Api.js:

import axios from "axios";

export function Api(props) {
    const result = axios({
        method: "get",
        url: props.URL,
    });

    return result;
}

App.js (or any other components)

import { useState, useEffect } from "react";
import { Api } from "./Api";

const URL =
    "https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=8a67ea6102e401ad62ded664a49689ec&text=cat&per_page=5&size=w&format=json";

function App() {
    const [flickr, setFlickr] = useState([]);

    function jsonFlickrApi(rsp) {
        if (rsp.stat != "ok") {
            return;
        }
        return rsp.photos.photo;
    }

    useEffect(() => {
        const flickr = Api({ URL })
            .then((e) => {
                setFlickr(eval(e.data));
            })
            .catch((er) => console.error(er));
    }, []);

    return (
        <div className="App">
            {flickr.map((r) => (
                <div key={r.id}>{r.title}</div>
            ))}
        </div>
    );
}

export default App;