-2

why react setState is not updating state in class component in my code

In the console, my data is shown (console.log(data))

but setState is not updating state

whats the problem

export default class Posts extends Component {
    constructor(props) {
        super(props)
        this.state = {
            posts: null,
            isPending: true
        }
    }

    componentDidMount() {
        fetch('http://localhost:5000/api/all_posts/')
            .then(response => response.json())
            .then(data => {
                console.log(data)
                this.setState({ posts: data });
            })
    }
    render() {
        return (
            <div className="posts">
                {this.isPending && <div>loading...</div>}
                {this.state.posts && this.state.posts.map((post) => {
                    <div className="post" key={post.id}>
                        {post.slug}
                    </div>
                })}
            </div>
        )
    }
}

Ali Rahmani
  • 41
  • 1
  • 4
  • What do you mean by not updating the state ? Did you put any console.log for `this.state.data` (inside the render method) to check whether it's an array of objects ? – Kavindu Vindika Oct 10 '21 at 15:41

2 Answers2

1

you have 3 errors.

  1. You are checking for this.isPending instead of this.state.isPending
  2. Your map function is not returning anything. Whenever you use curly braces ({}) you need to add the return keyword. If you don't use the curly braces you should use an implicit return which is done by using parenthesis around your returned object/component. So change it to this...
render() {
        return (
            <div className="posts">
                {this.state.isPending && <div>loading...</div>}
                {this.state.posts && this.state.posts.map((post) => (
                    <div className="post" key={post.id}>
                        {post.slug}
                    </div>
                ))}
            </div>
        )
    }
  1. Finally, when you set the value of the posts after the API call in the componentDidMount, you should set the isPending to false. So something like this...
  componentDidMount() {
    fetch("/api/all_posts/")
      .then((response) => response.json())
      .then((data) => {
        this.setState({ posts: data, isPending: false });
      });
  }
Ignacio Elias
  • 578
  • 4
  • 9
0

You put this.isPending instead of this.state.isPending

Nacho
  • 870
  • 6
  • 9