api - Ajax call returns undefined -
i trying make api call , following errors ajax not being function:
import $ 'jquery'; const apicall = function () { var url = 'https://images.nasa.gov/#/search-results'; var request = { q: 'sun', media_type: 'image' }; var result = $.ajax({ url: url, datatype: 'json', data: request, type: 'get' }) .done(function() { alert(json.stringify(result)); }) .fail(function() { alert('failed'); }) } module.exports = apicall; i importing above in module , calling on button click in react's render() function like:
import apicall './../api/apicall'; class gallery extends react.component { render () { return ( <section id="gallery" classname="g-site-container gallery"> <div classname="grid grid--full"> <div classname="gallery__intro"> <button extraclass="" type="button" handlebuttonclick={apicall} /> </div> </div> </section> ) } } module.exports = gallery; any thoughts doing wrong?
in experience, type of issue because transpilation not working might expect - or transpiling code while using jquery (or other lib) including cdn link. if case, here's info might sort out:
first, check transpiler pulling jquery in. having on page won't allow code work - because when transpiler operates on:
import $ 'jquery' it's going expect first load jquery package node_modules , create internal name it, such $_1 used inside bundle. if intend include jquery on page via cdn, rather bundling in fashion, need mark external in webpack or rollup config. if using webpack, like:
{ entry: '/path/to/your/application.js', externals: { 'jquery': '$', } } this tells webpack, "when import 'jquery', don't in node_modules - instead, assume jquery exists on page window.$. now, webpack won't attempt include , bundle of jquery lib - , instead of creating $_1 honor $ is.
if do intend load , bundle jquery part of build (not recommended, due incredible size-bloat entail) - suggest ensuring it's installed in node_modules. can with:
npm install -s jquery or, if you're using yarn:
yarn add jquery now, import statement should load lib correctly when re-transpile.
Comments
Post a Comment