Alk
Alk

Reputation: 688

React Component not updated when state changes

I have an input waiting for a URL and a dropdown list. Depending on the URL, the list in the dropdown will be different. I created a component (LocationSelector) for the dropdown. When loading the page the input is empty.

My problem is that when I'm putting a URL in the input and the state data gets updated, the component doesn't update.

Here is the code of the page (I cut some parts) that handles the input :

import React, { Component } from "react";
import LocationSelector from "../component/location-selector";

class Manage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      ProductURL: ""
    };

    this.handleChange = this.handleChange.bind(this);
    this.addProduct = this.addProduct.bind(this);
  }

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  addProduct(event) {
    // Do stuff
  }

  render() {
    return (
      <div className="col-md-6">
            <div className="row">
              <div className="col-md-12">
                <h2 className="bottom-separator">Add a product</h2>
              </div>

              <form onSubmit={this.addProduct}>
                <div className="col-md-12 margin-bottom-10">
                  <label>URL :</label>
                  <input
                    type="text"
                    className="form-control"
                    name="ProductURL"
                    value={this.state.ProductURL}
                    onChange={this.handleChange}
                  />
                </div>
                <div className="col-md-12 margin-bottom-10">
                  <LocationSelector
                    label="Shop"
                    location={this.state.ProductURL.split(".")[1]}
                  />
                </div>
                <div className="col-md-12">
                  <input
                    type="submit"
                    value="Submit"
                    className="btn btn-primary"
                  />
                </div>
              </form>
            </div>
          </div>
    );
  }
}

And here is the code of my component LocationSelector :

import React, { Component } from "react";

var data = require("../service/data");

class MySelectOptions extends Component {
  /**
   * Returns an Option element containing an ActorLocation to put in a Select element.
   * @props :
   *  -data.id : the id of the ActorLocation (ex : "5001")
   *  -data.value : the name of the ActorLocation (ex : "NY")
   *  -data.subvalue : the subtext of the ActorLocation (ex : "subtext")
   */

  render() {
    return (
      <option
        data-subtext={this.props.data.subvalue}
        value={this.props.data.id}
      >
        {this.props.data.value}
      </option>
    );
  }
}

class LocationSelector extends Component {
  /**
   * Returns a dropdown menu filled with the ActorLocation of a specific Actor.
   * @props :
   *  -label : the name of the Actor written in a normal way (ex : "My Actor")
   *  -location : the name of the Actor to be put in the URL request (ex : "myactor")
   */

  constructor(props) {
    super(props);

    this.state = {
      locations: []
    };
    this.componentDidMount = this.componentDidMount.bind(this);
    this.componentWillUnmount = this.componentWillUnmount.bind(this);
  }

  componentDidMount() {
    let vm = this;

    this.request = data.actors.get(vm.props.location).then(function(data) {
      var items = [];
      if (!jQuery.isEmptyObject(data)) {
        data.locations.forEach(function(location) {
          items.push({
            id: location.id,
            value: location.name,
            subvalue: location.subText
          });
        });
      }
      vm.setState({ locations: items });
      $(".selectpicker").selectpicker("refresh");
    });
  }

  componentWillUnmount() {
    if (this.request) {
      this.request.cancel();
    }
  }

  render() {
    var i = 0;
    var mySelectOptions = function(result) {
      return <MySelectOptions key={i++} data={result} />;
    };

    let selectId = "locationSelector" + this.props.label.replace(" ", "");

    return (
      <div>
        <label htmlFor="products">{this.props.label}:</label>
        <select
          id={selectId}
          className="selectpicker show-tick"
          data-live-search="true"
          data-size="5"
        >
          {this.state.locations.map(mySelectOptions)}
        </select>
      </div>
    );
  }
}

export default LocationSelector;

Thanks for your help !

Edit

Here is an almost workin CodeSandbox : https://codesandbox.io/s/m4x04mw3wx

Upvotes: 2

Views: 4540

Answers (1)

LaPoule
LaPoule

Reputation: 323

You need to use React lifecycle updating methods to perform that. See : https://reactjs.org/docs/react-component.html#the-component-lifecycle

Add this in your LocationSelector class :

componentWillReceiveProps(newProps){
    this.setState({
        location: newProps.location
    })
}

Upvotes: 4

Related Questions