1

I am using axios in react to get information from a django backend, I am getting the user data and I am storing it in a state in the component but I want to use one of the attributes in the user_data state in the url of another get to get more information from the backend, I do not know if I explained it correctly but here is the code :

state = {
    user_data: [],
    classes: []
  }
  
  componentDidMount() {
    const config = {
      headers: {
          'Content-Type': 'application/json',
          'Authorization': `JWT ${localStorage.getItem('access')}`,
          'Accept': 'application/json'
      }
    };
    axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
      .then(
        res => {
          this.setState({
            user_data: res.data
          });
        }
      )     
    const myString = this.state.user_data.SectionNumber
    axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
      .then(
        res => {
          this.setState({
            classes: res.data
            });
            console.log(res.data);
         }
      ) 
  }

I do not know how to change the state object into something that axios can understand and use in the url

2
  • is there any error that you are facing ? Commented Nov 13, 2020 at 11:06
  • You should pass the second call to fetch the class details as a callback to the first setState. Commented Nov 13, 2020 at 11:12

4 Answers 4

1

At this point when you are fetching the user related data you do not need to depend on the state. You can pass the second call as a callback to the first setState so that it can update it when the promise resolves and state has been updated.


axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
    .then(
        res => {
            this.setState({
                user_data: res.data
            });
        }, () => {
            const myString = this.state.user_data.SectionNumber
            axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
                .then(
                    res => {
                        this.setState({
                            classes: res.data
                        });
                        console.log(res.data);
                    }
                )
        }
    )
Sign up to request clarification or add additional context in comments.

1 Comment

It worked but not exactly as you said, I am going to put the code as an answer if anyone in the future needs it
0

You don't need to set the state and then take from the state to use this parameter in your url. You can use promises and pseudo-synchronous code async/await and it should help.

 async componentDidMount() {
  const config = {
     headers: {
        'Content-Type': 'application/json',
        'Authorization': `JWT ${localStorage.getItem('access')}`,
        'Accept': 'application/json'
     }
  };
  const userDataResponse = await axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
  const myString = userDataResponse.data.SectionNumber;
  const classesResponse = await axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
  this.setState({
     user_data: userDataResponse.data,
     classes: classesResponse.data
  });
}

Comments

0

This is the code that worked with me

axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
      .then(
        res => {
          this.setState({
            user_data: res.data
          });
          const SectionNumber = this.state.user_data.SectionNumber
          axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${SectionNumber}`, config)
            .then(
              res => {
                this.setState({
                  classes: res.data
                });
              }
            )
        } 
      )

Comments

0

I am also facing a similar problem and i have done exactly as you have shown but I do not see the results.

 axiosInstance.get('/user/profile/' + this.state.adminCard).then(response => {
                    axiosInstance.defaults.headers['Authorization'] = "JWT " + response.data.access;  
                    this.setState({
                        fullName: response.data.lastName + ", " +  response.data.firstName,
                        diploma:  response.data.diploma,
                        projectSlug:  response.data.project
                    })
                }, () => {
                    const slug = this.state.projectSlug;
                    axiosInstance.get('/user/project/' + slug).then(response => {
                        axiosInstance.defaults.headers['Authorization'] = "JWT " + response.data.access;  
                        this.setState({
                            assignedProjectName: response.data.projectName,
                            assignedProjectDesc: response.data.projectDesc,
                            assignedProjectSupervisor: response.data.projectSupervisor
                        })
                        console.log(this.state.assignedProjectName)
                    })
                })

On the line where I console.log(this.state.assignedProjectName), I do not even get a return, please advice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.