1

When I try to .map the image i get from the parent component so as to render the images gotten from unsplash, i get a type error .map is not a function error. I have attached code for the problem. if error is solved it is meant to show the images from the search bar

import React, { useState } from 'react';
        import axios from 'axios';
        import SearchBar from '../SearchBar/SearchBar';
        import ImageList from '../ImageList/ImageList';

        const API_KEY = process.env.REACT_APP_ACCESS_KEY;

        const SearchPage = () => {
          const [searchText, setSearchTerm] = useState('');
          const [image, setImage] = useState([]);

          const onInputChange = (e) => {
            setSearchTerm(e.target.value);
          };

          const fetchImages = () => {
            axios.get('https://api.unsplash.com/search/photos', {
              params: { query: searchText },
              headers: {
                Authorization: API_KEY,
              },

            })
              .then((data) => {
                setImage(data.data);
              });
          };
          console.log(image);
          const onSubmitHandler = (e) => {
            e.preventDefault();
            fetchImages();
          };

          return (
            <div>
              <SearchBar
                onSubmitHandler={onSubmitHandler}
                onInputChange={onInputChange}
                searchText={searchText}
              />

              <ImageList image={image} />

            </div>

          );
        };
        export default SearchPage;
    ---------------------------------------------------------------------
    /* eslint-disable jsx-a11y/alt-text */
    /* eslint-disable react/prop-types */
    import React from 'react';

    const ImageList = ({ image }) => {
      const imgs = image && image.map(img => (
        <img
          key={img.id}
          src={img.urls.regular}
        />
      ));
      return (
        <div>
          {' '}
          {imgs}
          {' '}
        </div>
      );
    };

    export default ImageList;

When I try to .map the image i get from the parent component so as to render the images gotten from unsplash, i get a type error .map is not a function error. I have attached code for the problem. if error is solved it is meant to show the images from the search bar

3
  • Try to console.log the image property Commented Jul 30, 2019 at 13:46
  • First of all, try removing the axios call, if no errors shows, this means the problem is in the response of that call. After, in axios call, add console.log(data.data) and add to your question what you see Commented Jul 30, 2019 at 14:18
  • Same as image an array from Unsplash Commented Jul 30, 2019 at 14:22

2 Answers 2

2

Because you have an async call, you need to check it before .map.

  const imgs = image && image.map(img => (
    <img
      key={img.id}
      src={img.urls.regular}
    />
  ));

Or what you could do is set the default value of image to an array.

// default value as an array []
const ImageList = ({ image = [] }) => {
  const imgs = image.map(img => (
    <img
      key={img.id}
      src={img.urls.regular}
    />
  ));
  return (
    <div>
      {' '}
      {imgs}
      {' '}
    </div>
  );
};

This might not working depending on what is the default value of image in the parent component.

A better aproach would be setting the default value of useState to [].

const [image, setImage] = useState([])

Edit:

As said in the comments by OP

I already had the image in the parent component initialized as an empty array.

So this means that when you do setImage(data.data);, data.data isn't an array.

Please check what is in data.data (maybe use console.log) and use the correct data you want to use .map.

Sign up to request clarification or add additional context in comments.

4 Comments

I already had the image in the parent component initialized as an empty array.
@SImonHaddad please check my edit. If it was already initialized as an empty array, this means that data.data probably isn't an array. Please check it
I console.logged images and it is returning an array
No its still the same problem, it seems its from the function .map will paste code now
0

A good practice for using map is to check the consistency that you will have an Array to map. Therefore, you can make a simple comparison to have a consistent array of your field =]

Change only your ImageList Component

const ImageList = ({ image }) => {

    const getImgs = () => (image.map(img => (
        <img
            key={img.id}
            src={img.urls.regular}
        />
    )));

    const imgs = typeof {} === 'object' && {}.length > 0 ? getImgs : <div>No images</div>;

    return (
        <div>
            {' '}
                {imgs}
            {' '}
        </div>
    );
};

2 Comments

It shows no images. So i console logged the typeof image in parent component and it shows object
Yes, I get it. In the case I answered only about how to get map consistency I ignored the render test. But if solved the problem is great, I will always be trying to help with what I can! Hugs!

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.