Ellipse
Ellipse

Reputation: 27

React ajax and jsx

My array that I filled with my ajax request result will not appears in my react components unordered list.

When I do a console.log of the array I get:

[] 0 : "Career"

1 : "Middle College for Technology Careers"

2 : "Careers New Zealand"

3 : "Careers for Veterans 200"

4 : "Northside Health Careers High School"

5 : "Barbie's careers"

6 : "Edward M. Kennedy Academy for Health Careers"

7 : "The Careers Group, University of London"

8 : "Careers advisor"

9 : "Careers advisory service"

length : 10

proto : Array[0]

When I call this array inside my react component it does not render. Here is my code below.

HTML

<div id="content"></div>

JS

// array that the titles will be loaded into
var response = [];

$.ajax({
    // request type ( GET or POST )
    type: "GET",

    // the URL to which the request is sent
    url: "https://en.wikipedia.org/w/api.php?",

    // data to be sent to the server
    data: {
        action: "query",
        format: "json",
        list: "search",
        srsearch: "careers",
        srwhat: "text",
        srprop: "timestamp",
        continue: "",
    },

    // The type of data that you're expecting back from the server
    dataType: "jsonp",
    crossDomain: true,
    // Function to be called if the request succeeds
    success: function (jsondata) {
        for (var i = 0; i < jsondata.query.search.length; i++) {
            //console.log( jsondata.query.search[i].title );
            //pushes each result into the array named list
            response.push(jsondata.query.search[i].title);
        }
    },
});

console.log(response);

var App = React.createClass({
    render: function () {
        //var title = list;
        return (
            <div>
                <h1>Hello World</h1>
                <p>The world is full of oppurtunity</p>
                <ul>
                    <li>{response[0]}</li>
                    <li>Freedom</li>
                    <li>Lozve</li>
                    <li>Money</li>
                </ul>
            </div>
        );
    },
});

ReactDOM.render(<App />, document.getElementById("content"));

Here is a link to my code pen where all my code is, http://codepen.io/vhall_io/pen/vKQrQN/ . I inserted response[0] into the first li tag and it will not render. Please help me render this.

Upvotes: 1

Views: 713

Answers (1)

Akash Bhandwalkar
Akash Bhandwalkar

Reputation: 901

You have to update state. It wont render is you are adding it to variable. as it is ajax call so your html render first

Upvotes: 1

Related Questions