skip to Main Content

First of all, this is my first question in StackOverflow, so sorry in advance for maybe not using the best format to ask it.

I am building a project using a django-rest api and a react server for the frontend that comunicates with it. I have some experience with Django and the API is working correctly, on the other hand I am completely new using react and I’m having a lot of troubles understanding it (I have only worked with AngularJS).

I have a custom class component (surfboard.jsx) which is called by the file App.js and I want to use a function in another file (surfboard.js) where I programmed the API requests with axios to obtain the object that a get request returns. But as it is an async function, the variable this.surfboard ends up containig a Promise instead of the response.data that I was expecting… How could I wait for the Promise to be resolved before assigning the response.data to the object?

Here is the constructor() funciton of the surfboard component class:

import React, {Component} from 'react'
import { getSurfboard } from '../../services/api/surfboards'
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button'






class Surfboard extends Component {

  constructor(props) {
    super(props);
    this.state = {
      name: "React",
    };
    this.onChange = this.onChange.bind(this);
    this.surfboard = getSurfboard(1);
    debugger
    this.editMode = props.editMode;
  }

....

And here is the API request funciton:

import axios from 'axios'

const getSurfboard = async(id) => {
    return await axios.get(`http://127.0.0.1:8000/api/surfboards/${id}/`).then( response => {
        console.log(response.data)
        return response.data
    }).catch( error => {
        console.error(error)
    })
}

export {
    allSurfboards,
    getSurfboard
}

I have tried the await method but still the object contains the promise with state pending. I did developed the class as a function before and used the useState and useEffect methods of react, but I had problems later rendering the data and modifying it.

2

Answers


  1. I don’t think it is possible to use the async/await in constructor.

    class Surfboard extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
          name: "React",
        };
        this.onChange = this.onChange.bind(this);
        this.editMode = props.editMode;
        getData();
      }
    
      getData = async () =>{
        this.surfboard = await getSurfboard(1);
        //or
        this.setState({surfboard: await getSurfboard(1)});
      }
    
    ....
    
    Login or Signup to reply.
  2. As you know api requests are asynchronous, that means the code will keep runing, even after the compiler reads the line in which the function was called, this is what Promises are used for.

    i’d recommend you follow the code below:

    Class Surfboard extends Component {
        constructor() {
            this.surfboard = null;
            this.loading = true;
        }
    }
    
    componentDidMount() {
         getSurfboard(1).then(res => {
              this.setState({
                  surfboard: res.data,
                  loading: false
              })
         })
    }
    [...]
    
    render() {
       return (
           <div>
               {this.state.loading === false && <Surfboard data={this.state.surfboard}/>}
           </div>
       )
    }
    

    That way, using componentDidMount we can run a functions as soon as react finishes loading the virtual dom, in this example there’s the function that makes the API call. I added a loading so we can explicitly state when the requested ended, when the API sends us the response we update the state and we can use the data in this.state.surfboard and because we waited until the promised resolved, this.state will contain the data you need

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search