0

I have a helpers file where I have a function that makes a GET request with axios. I am importing this function to a class and using it within a componentDidMount() method and setting the response as the state.

However, when I debug the code to see why I don't get the data from the request I see that the request is returning: Promise {<pending>} and leaving the state with a promise and giving me bugs in child components of this class.

How can I get the data from the request and not a promise?

Here is the code of the GET request:

export const GetRequest = (params) => {
    const url = `/api/v1/${params}`

    return axios.get(url)
        .then(response => {
            return response.data.data.attributes
        })
        .catch( error => {
            console.log(error)
        })
}

Here is the code from the class:

import React from 'react';
import UpdateForm from './UpdateForm'
import {GetRequest} from "../../utils/requests";
import axios from "axios";

export default class UpdateContact extends React.Component {
    componentDidMount() {
        const slug = this.props.match.params.slug
        const url = "contacts/" + slug + ".json"

        const response = GetRequest(url)
        this.setState({ contact: response })
    }

    render() {
        return(
            <UpdateForm contact={this.state}/>
        )
    }
}
problems
  • 95
  • 1
  • 8
  • A Promise is a promise that you will have a value at some future time. You **can't** have it **now**. Set the state with `then()` – Quentin Jul 29 '21 at 14:53
  • I have other get requests that return the data, I tought maybe there was another way to implement the get request to not get a promise, but thank you @Quentin – problems Jul 29 '21 at 14:57
  • No need for Axios. Not only is it an external library, but personally I got too many problems with it. Use the native fetch and drop the old `.then()` syntax. `const response = await fetch(url); const data = await response.json(); this.setState({ contact: data.attributes })`, job done. – Jeremy Thille Jul 29 '21 at 15:00
  • should I add it within `componentDidMount`? @JeremyThille – problems Jul 29 '21 at 15:03

0 Answers0