How can I get the state from `componentDidMount `(using Redux)?

Viewed 120

I'm quite new to React and Redux, so maybe the question is very obvious.

I tried to get some information by user id from my server using fetch API in componentDidMount

I have no problem with local state of DC - I need to get user id from Redux

import React from 'react';
import {connect} from 'react-redux';
class DrinkPage extends React.Component {
  constructor() {
    super();
    this.state = {
      DCs: [],
    };
  }
  async componentDidMount() {
    const response = await fetch(
      `http://localhost:5000/api/drinks/users/${this.props.currentUser.id}`,
    );
    console.log(this.props.currentUser.id);
    const json = await response.json();
    await this.setState({DCs: json.drinkCons});
  }
  render() {
    const DC = this.state.DCs;
    console.log(this.props.currentUser, 'render');
    return (
      <div className="App">
        <CardList DCs={DC} />
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});
export default connect(mapStateToProps)(DrinkPage);

But when I try to get the state of the current user from componentDidMount() it is null. In render, it actually shows the state.

What should I do to get the state from componentDidMount() and successfully get the information from the server?

1 Answers

I found an answer.

I should have used componentDidUpdate() instead of componentDidMount()

And also it is needed to check the state to avoid an infinite loop.

So finally the componentDidUpdate() should be like this:

    async componentDidUpdate() {

        const response = await fetch(`http://192.168.0.16:5000/api/drinks/users/${this.props.currentUser.id}`);
        const json = await response.json();
        if (this.state.DCs.length === 0) {
            await this.setState({ DCs: json.drinkCons });
        }
    }
Related