0

I have a requirement wherein I need to load the data through an ajax call to server and then pass on the data to reducer to render my page through props.

But I see the data in the ajax call is being shown as undefined.

function getInitData(url) {
    axios({url: url, timeout: 20000, method: 'get', responseType: 'json'})
    .then(function(response) {
        console.log(response.data.results)//--DATA DISPLAYED
        return response.data.results
    })
    .catch(function(response) {
        console.error(response.data);
    })
}

let formActions = {
    loadInitJSONSchema: function(formSchema) {
        let dataLoaded = getInitData('/startInterview')
        console.log(dataLoaded);//--DATA DISPLAYED as UNDEFINED
        return {type: 'LOAD_INIT_JSON_SCHEMA', formSchema: dataLoaded}
    }

}

I dont know why my data displayed as undefined in my actual method may be it is because of the asynchrnous call?? If so how do I load my data in actions??

Please find the complete code at the URL

Pathfinder
  • 934
  • 1
  • 12
  • 23

1 Answers1

1

It's promises all the way down.

A jQuery example: jQuery('body') does not return the body element. It returns a jQuery collection. jQuery('body').css('background', 'red'); also returns a jQuery collection. It's collections all the way down.

axios.get().then(function(response) { return response; }) does not return response. It returns a promise.

First, change this, to return the promise:

function getInitData(url) {
    return axios...

Then change your function:

loadInitJSONSchema: function(formSchema) {
    return getInitData('/startInterview').then(function(data) {
        return {type: 'LOAD_INIT_JSON_SCHEMA', formSchema: data}
    })

Then anyone who uses loadInitJSONSchema gets the promise and gets the value in a .then().

loadInitJSONSchema(schema).then(function(result) { ... do something with result })

It's promises all the way down.

This flow is asynchronous. With var something = axios.get().then(function(response) { return response; }) the code is evaluated in place and the program keeps going. The .then() callback happens at a later time, long after the current function has finished executing.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138
  • I've changed it to function getInitData(url) { return axios.get(url) } and loadInit.. as per given above... But I get an error saying Actions must be plain objects. Use custom middleware for async actions. – Pathfinder Mar 18 '17 at 19:14
  • Yup. Use something like https://github.com/gaearon/redux-thunk to let you return promises from your redux action creators, where the promise fulfils with a redux action. That's unrelated to this question. – Andy Ray Mar 18 '17 at 19:21