I'm new in ReactJS and JavaScript and I'm trying to pass ID through URL to "UserInfo.js", next I'm trying to get this ID in "GetUser.js" and by this ID ask API to show me informations (such as login, id, etc.) from DataBase. I have problem with React. API works fine in swaggerUI.
Code of GetUser.js:
import React,{ Component } from 'react';
import { stringify } from 'uuid';
import UserInfo from './UserInfo';
export class GetUser extends Component{
constructor(props){
super(props);
this.state = {
id: null,
userTable: [],
};
}
componentDidMount(){
var test = <UserInfo/>;
this.state.id = test;
this.GetUserById();
}
GetUserById(){
let id;
fetch(process.env.REACT_APP_API 'User/' {id},{
method:'GET',
header:{'Accept':'application/json',
'Content-Type':'application/json'}
})
.then(response=>response.json())
.then(data=>{
this.setState({userTable:data});
});
}
render(){
return(this.state.id)
}
}
Code of UserInfo.js
import React from 'react';
import { useParams } from 'react-router-dom';
function UserInfo(){
let { id } = useParams();
return (id);
}
export default UserInfo;
Routing:
import React, {Fragment} from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import {LoginPage} from './LoginPage';
import {Home} from './Home';
import UserInfo from './UserInfo';
import {Users} from './Users';
import {AddUser} from './AddUser';
import {GetUser} from './GetUser';
import {Profile} from './Profile';
function Routers() {
return (
<Router>
<Fragment>
<Routes>
<Route exact path='/' element={<LoginPage/>}/>
<Route exact path='/Home' element={<Home/>}/>
<Route exact path='/Uzytkownicy' element={<Users/>}/>
<Route path='/DodajUzytkownika' element={<AddUser/>}/>
<Route exact path="/Uzytkownicy/:id" element={<GetUser/>} component={UserInfo}/>
<Route path='/Profil' element={<Profile/>}/>
</Routes>
</Fragment>
</Router>
);
}
export default Routers;
Only what I got from console is "[object Object]" or errors of Hooks Picture of errors in network
CodePudding user response:
Try this in the fetch:
fetch(process.env.REACT_APP_API `User/${id}`,{
method:'GET',
header:{'Accept':'application/json',
'Content-Type':'application/json'}
})
Notice to " ` " around URL.
Tell me, did it help you?
CodePudding user response:
In a React class component, you can access the parameters using this.props.location.search
.
You can parse the result like so:
new URLSearchParams(this.props.location.search).get("id")
I would not try to access React hooks (like useParams
) in a class component. The purpose of hooks in React is to provide state and lifecycle methods to functional components, but class components already have these things.
You are creating a functional component (UserInfo
) purely so that you can call a hook so that you can access state that your class component already has access to.