How to pass state values via the axios get url in React?

All we need is an easy explanation of the problem, so here it is.

I’m now to react I want to pass a value via Axios URL which has been saved as a state. How can I pass this value? I retrieve empno via the get method by passing the id from a previous link;

 componentDidMount() {
    this.retrievePosts();
  }

  retrievePosts() {
    const id = this.props.match.params.id;
    console.log(id);
    axios.get(`http://localhost:5000/employees/${id}`).then(res => {
      if (res.data.success) {
        this.setState({
          empno: res.data.employee.empno,
          
        });
      }
    });

Im trying to pass empno in the same retrievePosts() method to get another value. I have currently implemented like this:

    axios.get(`http://localhost:5000/employees/alocation/${this.state.empno}`).then(res => {
        if (res.data.success) {
          this.setState({
              totalallocation: res.data.allocationcount,
            });

            console.log(this.state.totalallocation);
          }
        });

  }

The value seem to never pass as its output goes as "undefined". how can pass the empno state value which has been received via the URL?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

you need to make your code asynchornous to make it work. add async like this

async   retrievePosts() {...}

and then await after each case of axios

Method 2

in order to get the corect value, the second "get" call must happen after the first one, but it isn’t (necessarily) the case here – so you have to options:

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply