Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Getting id null while calling a request in reactjs v6 or this.props.match.params.id not working
class TodosComponent extends Component{

constructor(props){
    super(props)
    this.state= {
     id: this.props.id,//here id is not getting properly set i think
     description: 'My name is prathvi',
     targetDate : moment(new Date()).format('YYYT-MM-DD')    
    }
    this.onSubmit = this.onSubmit.bind(this)
    this.validate = this.validate.bind(this)
   }
   componentDidMount(){
   let username = AuthenticationService.getUserLoggedIn();
    TodoDataService.retriveTodo(username,this.state.id)//while calling   
  request i am getting error bcoz id is going as undefined
   .then(response=> this.setState({
    description : response.data.description,
    targetDate : moment(response.data.targetDate).format('YYYT-MM-DD') 
    }))
     }

//code for calling spring boot service

 import axios from "axios";
 class TodoDataService{
retriveAllTodos(name){
return axios.get(`http://localhost:8080/users/${name}/todos`)
}

retriveTodo(name,id){
return axios.get(`http://localhost:8080/users/${name}/todos/${id}`)
}

deleteTodos(name,id){
return axios.delete(`http://localhost:8080/users/${name}/todos/${id}`)
}


}
 export default new TodoDataService();

Questn: In above class TodoComponent inside this.state i have declared id, which is returning null when I am calling a request getting this error : GET http://localhost:8080/users/prathvi/todos/undefined 400. Actually I am a beginer and I am watching tutorial and making the program. He is using react 5 and am having react 6. Actually he is using id: this.props.match.params.id inside this.state. And if I am using it i am getting this error TodosComponent.jsx:12 Uncaught TypeError: Cannot read properties of undefined (reading 'params'). Can anyone help me what to use to solve this error. I have gone through multiple post but not getting this error solved.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The issue is why id is returning undefined is : I have not injected params to my class. And I am trying changes to same class TodosComponent class by making id: this.props.match.params.id, or trying different thing at componentDidMount function. You can see the question, how I was using it.

Below is my working code: For V6 STEP1: initialise id like below

class TodosComponent extends Component{

constructor(props){
    super(props)
    this.state= {
     id: this.props.params.id,//initialisg id in react v6
     description: 'My name is prathvi',
     targetDate : moment(new Date()).format('YYYT-MM-DD')
        
    }
     console.log(this.props.params.id) 
    }
    //remaing code of class which is not useful.

STEP2: Create a file with withParams.jsx or other name with .jsx extension and paste below code.

 import { useParams } from "react-router-dom";

  function withParams(Component) {
 return props => <Component {...props} params={useParams()} />;
 }

 export default withParams

STEP3: inject useParams to a place where you have declare Routing info

import withParams from './withParams'
class TodoApp extends Component {
 render() {
   
    const TodosComponentWithParams = withParams(TodosComponent);//this is how we 
    are injecting the class which we declare in step1
   
    return (

        <div className='TodoApp'>
            
            <Router >
            
                <Routes>

                    <Route path='/todos/:id' element={<AuthenticateRoute> 
                //using here    <TodosComponentWithParams/></AuthenticateRoute>} 
         />
                    
                </Routes>
            </Router>
           
        </div>
         );
         }}
      export default TodoApp;

Now after doing this if you run the code the console.log statement of class TodosComponent instead of printing undefind , it will print the value.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda