FDjawid
FDjawid

Reputation: 261

Using componentDidUpdate to change the state in the component

I have two components placed in a container. One is calling the Id of a publication and the other is calling a date of an issue from that specific publicationId.

When i called an Id for example the 100 then it will also load the issues from that Id. After that i can also filter on issueDate. But when i change the component with the Id again to have other list of issues then it won't rerender the component with the issues.

I heard that this problem is solved when using componentDidMount but i don't know what to do after this step:

 public componentDidUpdate(): void {
    const{ data, date } = this.state
    if (this.state.data !== data) {

//don't know what to do in this if statement

} 

This is the code to get publication Id with axios:

 constructor(props: TTestProductionProgressStatus) {
    super(props);
    this.state = {
      date: null,
      data: undefined,
      prodItem: []
    };
  }

  public componentDidMount(): void {
    const urlDate = this.props.location.pathname.split("/")[3];
    const date = urlDate
      ? new Date(
          `${urlDate.substr(0, 4)}-${urlDate.substr(4, 2)}-${urlDate.substr(
            6,
            2
          )}T00:00:00.000+01:00`
        )
      : null;
    axios
      .get<Definitions.ProductionProgressStatus[]>(
        "http://app30:665/v1/productionProgressStatus/crud?publicationId=" +
          this.props.id
      )
      .then(res => {
        this.setState(
          {
            data: res.data
          },
          () => this.handleDateChange(date)
        );
      })
      .catch(error => console.log(error.response));
  }

Upvotes: 0

Views: 265

Answers (1)

Jacob
Jacob

Reputation: 78920

The first thing to address is that your comparison is incorrect:

const{ data, date } = this.state
if (this.state.data !== data) {

Here you're comparing this.state.data with this.state.data; you're just extracting it two different ways, but it's the same properties you're comparing. The way to compare old versus new state is via the parameters passed to componentDidUpdate:

componentDidUpdate(prevProps, prevState) {
  if (this.state.data !== prevState.data) {

As to what you do in the if statement, you're probably wanting to make some kind of call to setState, which will cause another update. Generally it's better to avoid cascading updates when possible so you don't provoke two different re-renders unnecessarily; in other words, if you find an opportunity to change things without using componentDidUpdate, that would be better.

Upvotes: 2

Related Questions