2

I'm currently stuck on a problem, I would like to be able to return what the fetch receives, for example :

{"data": [{"account_id": 134519399, "account_url": "Pseudo", "ad_type": 0, "ad_url": "", "animated": false, "bandwidth": 110238, "datetime": 1603190775, "deletehash": "Mg3FROsdfPF7N", "description": null, "edited": "0", "favorite": false, "has_sound": false, "height": 368, "id": "3HzN2Ye", "in_gallery": false, "in_most_viral": false, "is_ad": false, "link": "https://i.imgur.com/lbWS8uo.jpg", "name": "unnamed.jpg", "nsfw": null, "section": null, "size": 55119, "tags": [Array], "title": null, "type": "image/jpeg", "views": 2, "vote": null, "width": 512}], "status": 200, "success": true}

but I'm currently receiving this:

{"_U": 0, "_V": 0, "_W": null, "_X": null}

here's my code:

export default async function FetchImage(access_token) {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + access_token);

var formdata = new FormData();

var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

try {
    const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
    // console.log(await response.text());
    return response.json
}
catch (err) {
    console.log('fetch failed', err);
}
}

And I call my function in this class :

var ress;
    export default class ImageNav extends Component {
    constructor(props) {
        super(props);
    }
 
    _getAccessToken() {
        var res = this.props.navigation.state.params.access_token;
        return res
    }
 
    render() {
        // console.log(this._getAccessToken())
        ress = FetchImage(this.props.navigation.state.params.access_token)
        console.log(ress)
        return (
            <>
                <View>
                    <Text>access_token: {this._getAccessToken()}</Text>
                </View>
                <View style={styles.buttonFav}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FavNav" onPress={() => this.props.navigation.navigate('FavNav')}></Button>
                </View>
                <View style={styles.buttonFind}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FindNav" onPress={() => this.props.navigation.navigate('FindNav')}></Button>
                </View>
            </>
        )
    }
}

I looked at these solutions :

How do I return the response from an asynchronous call?

async/await implicitly returns promise?

But I still can't solve my problem,

If someone could help me

Thank you !

Chaffy
  • 182
  • 12
HugoTek
  • 41
  • 5

3 Answers3

0

response.json() is also Promise. So you should attach await in front of it.

export default async function FetchImage(access_token) {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + access_token);
myHeaders.append("Content-Type", "application/json");

var formdata = new FormData();

var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

try {
    const response = await fetch("https://api.imgur.com/3/account/me/images", requestOptions)
    // console.log(await response.text());
    return await response.json()
}
catch (err) {
    console.log('fetch failed', err);
}
}
Prime
  • 2,809
  • 1
  • 7
  • 23
0

Ok @Prime, I just saw, that my solution creates the same problem afterwards

 async _getData() {
    try {
        this.state.test = await FetchImage(this.props.navigation.state.params.access_token);
        console.log(this.state.test.data[0]["link"])
        return (this.state.test)

    } catch (error) {
        console.error(error);
    }
    // console.log(res)

}

I call him here :

render() {
        try {
            console.log(this._getData())
            
        } catch (error) {
            console.error(error);
        }
        console.log("ici = " + this.props.test)
        return (
            <>
                <View>
                    <Text>access_token:</Text>
                </View>
                <View style={styles.buttonFav}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FavNav" onPress={() => this.props.navigation.navigate('FavNav')}></Button>
                </View>
                <View style={styles.buttonFind}>
                    <Button buttonStyle={{ backgroundColor: '#4D4D4D' }} title="FindNav" onPress={() => this.props.navigation.navigate('FindNav')}></Button>
                </View>
            </>
        )
    }
}

But, When I try to use what is stored in my 'this.state.test', it is 'undefined'.

console.log(this._getData()) display this {"_U": 0, "_V": 0, "_W": null, "_X": null}

I am desperate :'(

HugoTek
  • 41
  • 5
0

Ok, i found the solution, I had to make a setState of what I was receiving.

async componentDidMount() {
        try {
            let res = await FetchImage(this.props.navigation.state.params.access_token);
            this.setState({ test: res })
        } catch (error) {
            console.error(error);
        }
    }

I put it in the componentDidMount() function so that the setState doesn't loop.

Thank you for all, Thank you very much @Prime.

HugoTek
  • 41
  • 5