0

I have a SubmitEvent class component which uses a service class for retrieving venues using Axios.

  export default class SubmitEvent extends React.Component {
  constructor(){
      super();
      this.state = {
          loggedIn: undefined,
          venues: []
      }
      this.checkLoggedIn.bind(this);
      this.getVenues.bind(this);
  }
  checkLoggedIn = () => {
    let token = localStorage.getItem("auth-token");
    if (token === "") {
      return false;
    }
    return true;
  };
  getVenues = async () => {
    let res = [];
    await Axios.get("/venues",{
      headers:{
        "Content-Type":"application/json",
      }
    })
    .then((response) =>{
      res = response.data
      console.log(res)
    })
    .catch(err => console.log(err))
    return res;
  }

  componentDidMount() {
    this.setState({
      loggedIn: this.checkLoggedIn(),
      venues: this.getVenues()
    });
    console.log(this.state.venues)
  }
}

If I am console logging the returned value in getVenues method the response is being shown. Although in the componentDidMount() the state for venues is is an empty array. Why is this happening and how can I solve this?

Razvan
  • 143
  • 8

2 Answers2

1

You could call the api and when the promise is fulfilled, set your state.

export default class SubmitEvent extends React.Component {
  constructor(){
      super();
      this.state = {
          loggedIn: undefined,
          venues: []
      }
      this.checkLoggedIn.bind(this);
      this.getVenues.bind(this);
  }
  checkLoggedIn = () => {
    let token = localStorage.getItem("auth-token");
    if (token === "") {
      return false;
    }
    return true;
  };
  getVenues = async () => {
    await Axios.get("/venues",{
      headers:{
        "Content-Type":"application/json",
      }
    })
    .then((response) =>{
       this.setState({ venues: response.data });
    })
    .catch(err => console.log(err))
  }

  async componentDidMount() {
    this.setState({
      loggedIn: this.checkLoggedIn(),
    });
    await this.getVenues();
  }
}

Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
1

You need to setState inside then:

getVenues = async () => {
    let res = [];
    await Axios.get("/venues",{
      headers:{
        "Content-Type":"application/json",
      }
    })
    .then((response) =>{
      res = response.data
      console.log(res)
      this.setState({venues: response.data})
    })

    .catch(err => console.log(err))
    return res;
  }

what you actually returned to venues in componentDidMount before, was a promise because of the async keyword of getVenues method.

zb22
  • 3,126
  • 3
  • 19
  • 34