Reputation: 358
This is my first app using AWS API gateway and I was able to pull data when the function was called within componentDidMount now I'm calling the module like this from my component class
componentDidMount (){
// debugger
this.setState({apiData: apiCall(this.state.testSearch) })
this.updateAPIdata()
}
and apiCall is a function in methods.js
const apiCall = function(searchInput) {
const searchTerm = searchInput
var apigClientFactory = require('aws-api-gateway-client').default;
const config = {
apiKey: 'xxxxxx',
invokeUrl:'https://xxxx.execute-api.us-east-2.amazonaws.com'
}
var apigClient = apigClientFactory.newClient(config);
var params = {
//This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
// userId: '1234',
search_keyword: 'Ambassador'
};
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = '/beta/testDB'
var method = 'GET';
var additionalParams = {
//If there are any unmodeled query parameters or headers that need to be sent with the request you can add them here
headers: {
},
queryParams: {
search_keyword: 'Ambassador'
}
}
debugger
apigClient.invokeApi(params, pathTemplate, method, additionalParams)
.then(function(result)
{
//This is where you would put a success callback
return JSON.parse(result.data)
}).catch( function(result){
//This is where you would put an error callback
})
}
when I debug the code all the right variables are passed to apigClient.invokeApi but it never goes to the then function it just jumps to the last closing } on the apiCall function. This is unexpected, as before it would debug the next like then(function(result).
Am I calling the function wrong or some other newbie mistake? This code worked when it was in the same .js file as componentDidMount.
Upvotes: 1
Views: 1160
Reputation: 1847
The issue is that you are returning your results only after resolving the response from your API, which happens asynchronously.
There are two ways to fix this
`
componentDidMount() {
apiCall(this.state.testSearch, (data, error) => {
if (error) {
//handle
console.log(error)
return
}
this.setState({apiData: data})
this.updateAPIdata()
}
}
const apiCall = function(searchInput, callback) {
//...Your code
apigClient.invokeApi(params, pathTemplate, method, additionalParams)
.then((result) => {
callback(JSON.parse(result.data))
})
.catch((error) => {
callback(null, error)
})
}
`
async componentDidMount() {
try {
const data = await apiCall(this.state.testSearch)
this.setState({apiData: data})
this.updateAPIdata()
} catch(e) {
//Handle error
}
}
async function apiCall(searchInput) {
//...Your code
const result = await apigClient.invokeApi(params, pathTemplate, method, additionalParams)
return JSON.parse(result)
}
Upvotes: 1