1

This is a local JSON file I wrote.

{ "data":[
    {
    "photo": "https://source.unsplash.com/aZjw7xI3QAA/1144x763",
    "caption": "Viñales, Pinar del Río, Cuba",
    "subcaption": "Photo by Simon Matzinger on Unsplash",
    "thumbnail": "https://source.unsplash.com/aZjw7xI3QAA/100x67",
    }, 
    {
    "photo": "https://source.unsplash.com/c77MgFOt7e0/1144x763",
    "caption": "La Habana, Cuba",
    "subcaption": "Photo by Gerardo Sanchez on Unsplash",
    "thumbnail": "https://source.unsplash.com/c77MgFOt7e0/100x67",
    },
    {
    "photo": "https://source.unsplash.com/QdBHnkBdu4g/1144x763",
    "caption": "Woman smoking a tobacco",
    "subcaption": "Photo by Hannah Cauhepe on Unsplash",
    "thumbnail": "https://source.unsplash.com/QdBHnkBdu4g/100x67",
    }
]
}

and I don't understand why can't I map value after resolving. I fetched data and resolved it, and when I call console.log(response.data) I do get the JSON object, but when I want to map it, it show me an error that photos.map isn't function.

import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios'

function FetchingData() {
    const [photos, setPhotos] = useState([]);

    useEffect(()=>{
        axios.get('photos.json')
        .then(response => {
            console.log(response)
            setPhotos(response.data)
        })
    })

    return (
        <div>
            <ul>
               {photos.map(photos => (<li>{photos.photo}</li>)
               )}
            </ul>
        </div>
    )
}

export default FetchingData
3
  • 1
    The first note is that your JSON is invalid, you can validate JSON online (E.g from here jsonlint.com ) Commented Jan 11, 2020 at 0:00
  • Christian's answer is the one. Put simply, EVERY axios response has the payload on its data property. Your payload happens to also have its own data property too. Commented Jan 11, 2020 at 3:54
  • @Az.Youness yes it was, a comma in the end, but it wasn't the main problem... Commented Jan 17, 2020 at 15:37

2 Answers 2

4

I believe you are missing a data. The response from the axios call will contain the payload (your JSON file) in data, i.e., response.data. However, that is an object (which has no map function). I believe you are after the array in your own data field, so try:

            setPhotos(response.data.data)
Sign up to request clarification or add additional context in comments.

Comments

1

If your json file contains a data field as an array, you need to call

setPhotos(response.data.data);

Otherwise, try to use JSON.parse() (even if I know axios automatically parse json as object, but you never know)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.