What's wrong with my API code?


I really need help and I’m new to coding. I’m trying to use an image api assigned to a search.

I’ve made an input field and button and I want the search results assigned to my gallery but I keep getting an error. I don’t know how to advance from here. Can someone help?

This is what my main page/ button code looks like:

import {unsplash} from ‘backend/serviceModule’
export function button2_click_1(event) {
let imageSearch = $w(‘#input1’).value;
(unsplash(imageSearch, 1))
.then( (imagesQuery) => {
$w(“#gallery1”).items = imagesQuery;
}); //Add your code for this event here:

And this is what my serviceModule.jsw backend looks like:

import {fetch} from ‘wix-fetch’;
let images = ;
export function unsplash (imageSearch, pageNum) {
var api = “https://api.unsplash.com/search/photos/?”;
var apiKey = “fffffffffffffffffff-fffffffffff-fffffffffffffffff”;
var search = “&query=” + imageSearch;
var perPage = “&per_page=30”;
var page = “&page=” + pageNum;
var url = api + apiKey + search + perPage + page;
return fetch (url, {method: ‘get’})
.then( (httpResponse) => {
if (httpResponse.ok) {
console.log(“HTTP OK”);
return httpResponse.json();
} )
.then( (json) => {
for ( var i = 0; i < json.results.length; i++) {
// console.log(json.results[i].urls.regular + page);
src: json.results[i].urls.regular,
description: json.results[i].description,
title: “Title” + i
return images;

I keep getting an error: Cannot read property ‘results’ of undefined. >> serviceModule.jsw line 23

This is line 23:

for (var i = 0; i < json.results.length; i++) {

Any help would be appreciated or if there’s a simpler way to write this code.

Thank you


It’s true that results hasn’t been declared in your code. Just change json.results.length to json.length . That should resolve the issue.

You may also have to user forEach instead of the for loop.

json.forEach((item) => {
			//Put images push code here

Good luck!