0

How can I get the json data from apiUrl? Need some help writing the function

changeUrl: function(evt){
        this.setState({
          value: evt.target.value,
          apiUrl: "https://test.holmusk.com/food/search?q=" + evt.target.value
        });
      },

      getJson: function() {

      },
1
  • 2
    You don't "use" react to get data from an API. React is just the view component. You can use javascript to make HTTP calls to get the data from your API. If you are doing a lot with data then I recommend looking into flux/redux/alt. There are plenty of http libraries to use out there. I like using github.com/mzabriskie/axios or you can even just use $.get(apiUrl, function(data) {}); Commented Apr 11, 2016 at 19:21

1 Answer 1

2

Your code is a bit confusing because it's hard to tell why you're setting apiURL in setState, when I assume you need to call that URL to get the Json data. The commenter makes a good point about setting up a data-retrieval architecture using a library like Redux. However, if you want to just do a plain-vanilla Javascript call, you could do something like below. It's hard to tell if you need the Json results in your component's state, but I'm guessing you do, so I rearranged the code with that assumption in mind.

    changeUrl: function(evt){
            getJson(evt.target.value);
    },

    getJson: function(newVal) {
        var request = new XMLHttpRequest();
        request.open('GET', "https://test.holmusk.com/food/search?q=" + newVal, true);
            request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');    
            //this callback gets called when the server responds to the ajax call            
            request.onreadystatechange = function(){
                if (request.readyState === 4 && request.status === 200){
                    var returnedJson = JSON.parse(request.responseText);
                    //this is where you would want to run setState if you need the returned Json for it.
                    setState({newJson: returnedJson});
                }
                else if (request.readyState === 4 && request.status !== 200){
                    alert('error');
                }           
            };      
            request.send();
    }
Sign up to request clarification or add additional context in comments.

Comments

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.