简体   繁体   中英

How to map over an array that is fetched using axios

I am working on a chat-app and is trying to make a fetch using axios for the first time. I have succeded in making the fetch because I see the array from the url when I console.logging it. However I want to map over all the messages in the array and display them for a user. But I am doing something wrong so the mapping dosent work. Can someone help me to see why?

This is my code (I belive that its the map-function that is creating the problem):

import React, { useState, useEffect } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import axios from 'axios'


export const GetMessages = () => {
  const [userName, setUserName] = useState([]);
  const [userMessage, setUserMessage] = useState([]);

  const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    console.log(getResponse)
    setUserMessage(getResponse)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  

  useEffect(() => {
    fetchResponse()
  }, [])

  console.log(userMessage)

  return (
    <div>
      {userMessage.map(message => (
        <p>{message.message}</p>
      ))}
    </div>
  )
  }

Some of the response in the array is object which make React fail to render. The 3rd to 5th items.

[
    {
        "message": "hej test"
    },
    {
        "message": "hej test",
        "id": "1"
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    }
]

It seems like you have message as an object within the array. You must check if its an object and then render the required field

import React, { useState, useEffect } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import axios from 'axios'


export const GetMessages = () => {
  const [userName, setUserName] = useState([]);
  const [userMessage, setUserMessage] = useState([]);

  const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    console.log(getResponse)
    setUserMessage(getResponse)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  

  useEffect(() => {
    fetchResponse()
  }, [])

  console.log(userMessage)

  return (
    <div>
      {userMessage.map(message => (
        <p>{message.message !== null && typeof message.message === 'object'? message.message.mess: message.message }</p>
      ))}
    </div>
  )
}

Actually when you use axios, the data returned is inside of an object called data. Just like like with the fetch API where you have to add .json() to the response, you also have to destructure the data out of axios response.

In your case, it should be something like this

const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    Const data = await getResponse.data
    Console.log(data)
    setUserMessage(data)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM