1

Given is an application with 3 pages:

  • "Mainpage"
  • "PrivatPage"
  • "UserManagementPage"

and a file for communication with the backend:

  • "ManagementAction.js"

After successful login the user is redirected to a "PrivatPage". On the "PrivatPage" the user has the possibility to go to the "UserManagementPage".

PrivatPage.js

import React, {
  Component
} from "react";

import LogoutButton from "./LogoutButton";
import UserManagementButton from "./UserManagementButton";
import ManagementSessionWidget from './UserManagementSessionWidget'
import UserManagementPage from './UserManagementPage'
import {
  NavBar,
  LinkContainer
} from 'react-router-bootstrap'
import Modal from "react-bootstrap/Modal";
import Form from "react-bootstrap/Form";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

import Button from "react-bootstrap/Button"

class PrivatePage extends Component {

  render() {

    return (

      <
      div className = "page-content"
      id = "PrivatePage"
      style = {
        {
          background: 'white'
        }
      } >

      
      <
      br / > Private Page <
      br / >
      <
      Router >

      <
      Button > < Link to = "/user"
      id = "OpenUserManagementButton" >
      <
      i className = "fa fa-user mr-2 fa-fw activityBarItem" > <
      /i>UserManagement</Link > < /Button> <
      Routes >

      <
      Route path = "/user"
      element = {
        < UserManagementPage / >
      }
      />

      <
      /Routes> <
      /Router>

      <
      /div>       

    )
  }
}

export default PrivatePage

However, when the "UserManagementPage" is opened, the backend data should appear on the page. Access to the backend data works. The "ManagementAction.js" file is used for this purpose

ManagementAction.js

export function showallUser(){

    console.log("Show all Users")
    return dispatch => {
        dispatch(getShowUserManagementAction());
        showUser().then(userSession => { const action= getShowUserManagementActionSuccess(userSession);
        dispatch(action);}, error => {dispatch(getShowUserManagementErrorAction(error));}).catch(error=> {dispatch(getShowUserManagementErrorAction(error));})
    }

    
}

function showUser() {
    const hash="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiJhZG1pbiIsImlzQWRtaW5pc3RyYXRvciI6dHJ1ZSwidXNlck5hbWUiOiJEZWZhdWx0IEFkbWluaXN0cmF0b3IgQWNjb3VudCIsImV4cGlyZXMiOjE2NDE1NjgyNzgxNDUsImlhdCI6MTY0MTU2Nzk3OH0.mJff9nuqgHXZVQfWbjeWed3JIRAm2N2s0CYpnXoMyv4"
    const requestOptions = {
        method: 'GET',
        headers: {  'Authorization': `Basic ${hash}` },
        
        }; 
        
         
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});


} 

I also tried to get the data from the API on the "UserManagementPage" with the help of the axios module. The data only do not arrive again,the console.log output returns an empty array.

   class UserManagementPage extends Component {

    constructor(props) {
        super(props);
        this.state = {userList: []}
    }

    async componentDidMount() {
        console.log("I will get called once the page gets loaded");
        const hash="whatever"
    const requestOptions = {
        method: 'GET',
        headers: {  'Authorization': `Basic ${hash}` },
        
        };
        const response =  await axios.get('https://localhost:443/user/', requestOptions);
        this.setState({ userList: response.data.results });
        console.log(this.state.userList)
    }}

How do I map the data to the "UserManagementPage" now ?

3 Answers3

1

to get the data from backend in UserManagementPage.js you should use the useEffect hook in which you will call your functions showUser or showAllUser.

Here is the link of doc: https://reactjs.org/docs/hooks-effect.html

Medamine
  • 129
  • 6
  • Hooks won't work, Pawl123 seems to be using class components. If you want to use hooks, make sure your UserManagementPage is a functional component, or instead call the showUser / showAllUsers methods from the componentDidMount lifecycle method. See https://stackoverflow.com/questions/38742334/what-is-right-way-to-do-api-call-in-react-js – Ben Ripka Jan 11 '22 at 20:57
  • Just now I tried to get the data directly on the UserManagementPage using the Axios module. Unfortunately it did not work. I have extended my post accordingly. –  Jan 11 '22 at 22:44
1

Looks to me like you have a capitalisation mismatch in your state? You initialise it as userlist, but then set the state under the key userList. The console log returns an empty array because the state variable you initialise never gets updated.

Robkwood
  • 345
  • 3
  • 5
  • 17
0

The successful fetching of data from the API was achieved with the following method:

   getUsersData() {

        const hash="whatever"
        const requestOptions = {
            method: 'GET',
            headers: {  'Authorization': `Basic ${hash}` },
            
            };
        axios
            .get('https://localhost:443/user/', requestOptions)
            .then(res => {
                const data = res.data
                console.log(data)
                
                const users = data.map(u =>
                    <div>
                    <p>{u.userID}</p>
                    
                    
                    </div>
                    )

                    this.setState({
                        users
                    })

            })
            .catch((error) => {
                console.log(error)
            })

    }

    componentDidMount(){
        this.getUsersData()
    }