2

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
    What Do you mean by "get the state"? Did you try `console.log(this.state.DCs)`? state changes are asynchronous, but you cannot `await` them (because they're batched together by React). You can however pass a function to `this.setState` as 2nd parameter, it will run after the change. –  Oct 09 '20 at 07:20
  • 2
    Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) –  Oct 09 '20 at 07:20
  • You could try not mounting the component when `props.currentUser` is not set. Not sure why you would try to get data for current user when you haven't set the user yet. – HMR Oct 09 '20 at 07:50

1 Answers1

0

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 });
        }
    }