javascript - TypeError: Cannot read properties of undefined (reading 'then') - Stack Overflow

I have an issue rendering this code in the browser, is there a way I can fix this? If there's more

I have an issue rendering this code in the browser, is there a way I can fix this? If there's more information needed, let me know? I receive the error at the ponentDidMount. Is there something I am doing wrong.

The PostService is posted at the bottom.

import React, { Component } from 'react';
import PostService from '../services/PostService';

class ListPost extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      posts: []
    };
  }
  
  ponentDidMount(){
    PostService.getPosts().then((response) => {
      this.setState({ posts: response.data });
    });
  }
  
  render() {
    return (
      <div>
        <h2 className="text-center">Posts</h2>
        <div className="row">
          <table className="table table--striped table-boarded">
            <thead>
              <tr>
                <th>Title</th>
                <th>Description</th>
                <th>Content</th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.posts.map(
                  post => 
                  <tr key={post?.id}>
                    <td>{post?.description}</td>
                    <td>{post?.title}</td>
                    <td>{post?.content}</td>
                  </tr>       
                )}
            </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default ListPost;


import axios from "axios";

const POST_API_BASE_URL = "http://localhost:8080/api/posts";

class PostService {
    getPosts() {
        axios.get(POST_API_BASE_URL);
    }
}

export default new PostService();

I have an issue rendering this code in the browser, is there a way I can fix this? If there's more information needed, let me know? I receive the error at the ponentDidMount. Is there something I am doing wrong.

The PostService is posted at the bottom.

import React, { Component } from 'react';
import PostService from '../services/PostService';

class ListPost extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      posts: []
    };
  }
  
  ponentDidMount(){
    PostService.getPosts().then((response) => {
      this.setState({ posts: response.data });
    });
  }
  
  render() {
    return (
      <div>
        <h2 className="text-center">Posts</h2>
        <div className="row">
          <table className="table table--striped table-boarded">
            <thead>
              <tr>
                <th>Title</th>
                <th>Description</th>
                <th>Content</th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.posts.map(
                  post => 
                  <tr key={post?.id}>
                    <td>{post?.description}</td>
                    <td>{post?.title}</td>
                    <td>{post?.content}</td>
                  </tr>       
                )}
            </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default ListPost;


import axios from "axios";

const POST_API_BASE_URL = "http://localhost:8080/api/posts";

class PostService {
    getPosts() {
        axios.get(POST_API_BASE_URL);
    }
}

export default new PostService();
Share Improve this question edited Nov 17, 2021 at 17:25 Steven McDonald asked Nov 17, 2021 at 17:09 Steven McDonaldSteven McDonald 111 gold badge1 silver badge3 bronze badges 6
  • 1 Can you share the contents of PostService file. You're either not exporting or importing your function properly. – Abdul Sadik Yalcin Commented Nov 17, 2021 at 17:12
  • Does getPosts return a promise? Seems like not, but without a minimal reproducible example it's hard to be more specific. – jonrsharpe Commented Nov 17, 2021 at 17:14
  • Can you also share the code of getPosts function ? – Anuj Raghuvanshi Commented Nov 17, 2021 at 17:15
  • import axios from "axios"; const POST_API_BASE_URL = "localhost:8080/api/posts"; class PostService { getPosts() { axios.get(POST_API_BASE_URL); } } export default new PostService(); – Steven McDonald Commented Nov 17, 2021 at 17:17
  • You should return the promise in your service method – Eldar Commented Nov 17, 2021 at 17:28
 |  Show 1 more ment

3 Answers 3

Reset to default 0

First of all change your PostService to;

import axios from "axios";
const POST_API_BASE_URL = "http://localhost:8080/api/posts";

export default function getPosts() {
  return axios.get(POST_API_BASE_URL);
}

And import as import getPosts from '../services/PostService'; on your ListPost class.

Then use the code below. You shouldn't be setting state inside ponentDidMount

ponentDidMount() {
  this.getData();
}

getData = () => {
  getPosts()
    .then(response => {
      this.setState({ posts: response.data });
    })
    .catch(error => {
      // handle errors here
    })
}

You don't have to change so many codes but just modify your codes of PostService file to:

import axios from "axios";

const POST_API_BASE_URL = "http://localhost:8080/api/posts";

class PostService {
    getPosts() {
        return axios.get(POST_API_BASE_URL);
    }
}

export default new PostService();

Let getPosts return a Promise instance instead of a undefined value, and then you could invoke then method after PostService.getPosts() inside ponentDidMount hook.

None of the above answers explain the underlying issue. The problem is that getPosts() is not explicitly returning a Promise.

getPosts() {
  return axios.get(POST_API_BASE_URL); // Added return
}

An alternate way to this:

async getPosts() {
  try {
    const response = await axios.get(POST_API_BASE_URL);
    return response.data;
  } catch (error) {
    throw error;
  }
}

This is why having correct types in place is of paramount importance.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745378763a4625125.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信