0

This is my SearchForm.js class, experience prop must be array of values with id and name

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class SearchForm extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
       position: '',
       area: '',
       date: '',
       experience: {
            type: Array,
            default: () => []
          }  
      }        
     }

    componentDidMount() {
        axios({
            method: 'GET',
            url: 'https://example.com/dictionaries/', 
            headers: { 
                'User-Agent': 'React App/1.0 ([email protected])', 
                'HH-User-Agent': 'React App/1.0 ([email protected])',  
                'Content-Type':'application/x-www-form-urlencoded',
            }
            })
          .then(function (response) {
            console.log(response.data.experience);
          })
          .catch(function (error) {
            console.log(error);
          });
    }


    render() {
        return ( 
            <form className='form search-form' onSubmit={this.handleSubmit}>
                <div className="form-row">         
                    <div className="form-group col-md-2">
                        <label htmlFor="experience">Experience</label>
                        <select className="form-control" name="experience" id="experience" onChange={this.handleExperienceChange} value={this.state.experience}>
                {/* <option key={this.props.experience.id} value={this.props.experience.name}>
                            {this.props.experience.name}
                        </option> */}
                        </select>
                    </div>
                </div>  
            </form>
        )
    }
}

export { SearchForm }

as result I get

enter image description here

How to put this values from response.data.experience in experience prop?

1
  • 1
    Use arrow functions, it'll lexically scope this. Change then((function(response) {...} to then((response) => {...} Commented Mar 20, 2018 at 8:59

3 Answers 3

2

You can change the state like

axios({
    method: 'GET',
    url: 'https://example.com/dictionaries/', 
    headers: { 
        'User-Agent': 'React App/1.0 ([email protected])', 
        'HH-User-Agent': 'React App/1.0 ([email protected])',  
        'Content-Type':'application/x-www-form-urlencoded',
    }
}).then((response) => {
    console.log(response.data.experience);
    this.setState({experience: response.data.experience})
}).catch(function (error) {
    console.log(error);
});

And you can loop through the experience array by using this :

{ this.state.experience.map((value, index) => <option key={value.id} value={value.name}> {value.name} </option> ) }

Sign up to request clarification or add additional context in comments.

8 Comments

TypeError: Cannot read property 'setState' of undefined at SearchForm.js:37 in this case
answer updated. You also need to bind the function to the class for use this inside
.then((response) => { this.setState({experience: response.data.experience}); console.log(this.experience); }) doesn't work either - Undefined in console
When I try console.log(this.experience); I get Undefined
for get values form state, use this.state.experience
|
1

experience is in your state, so you have to use the setState method like :

this.setState({experience: response.data.experience})

3 Comments

TypeError: Cannot read property 'setState' of undefined at SearchForm.js:37 in this case
it is a scoping issue. you need to declare var _ this = this; outside the callback and use _this in the callback
Yes, or you can use arrow functions.
1

Does this solution work for you ? Let me know!

Edit: Added conditional rendering for your <option> if your experience is not yet defined

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";

class SearchForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        position: "",
        area: "",
        date: "",
        experience: {
            type: Array,
            default: () => [],
        },
    };
}

componentWillReceiveProps = NextProps => {
    if (NextProps.experience !== this.props.experience) {
        this.setState({ experience: NextProps.experience });
    }
};

componentDidMount() {

    axios({
        method: "GET",
        url: "https://example.com/dictionaries/",
        headers: {
            "User-Agent": "React App/1.0 ([email protected])",
            "HH-User-Agent": "React App/1.0 ([email protected])",
            "Content-Type": "application/x-www-form-urlencoded",
        },
    })
        .then(response => {
            console.log(response.data.experience);
            this.setState({ experience: response.data.experience });
        })
        .catch(function(error) {
            console.log(error);
        });
}

render() {
    return (
        <form className="form search-form" onSubmit={this.handleSubmit}>
            <div className="form-row">
                <div className="form-group col-md-2">
                    <label htmlFor="experience">Experience</label>
                    <select
                        className="form-control"
                        name="experience"
                        id="experience"
                        onChange={this.handleExperienceChange}
                        value={this.state.experience}
                    >
                        {this.state.experience.length > 0 && 
                        <option
                            key={this.state.experience.id}
                            value={this.state.experience.name}
                        >
                            {this.state.experience.name}
                        </option> }
                    </select>
                </div>
            </div>
        </form>
    );
}
}

8 Comments

TypeError: Cannot read property 'setState' of undefined at SearchForm.js:37 in this.setState({ experience: response.data.experience });
Updated my answer, what does it say now ? Could be a this scope issue
I used your code .then((response) => { this.setState({experience: response.data.experience}); console.log(this.experience); }) but console.log(this.experience); - undefined
You need to do: .then((response) => { this.setState({experience: response.data.experience}, () => console.log(this.state.experience));
ok, it helped. but {this.state.experience.length > 0 && <option key={this.state.experience.id} value={this.state.experience.name} > {this.state.experience.name} </option> } doesn't work, options are empty
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.