Home > Software engineering >  React mapping not running the array
React mapping not running the array

Time:11-14

Need some help here with React, I'm trying to fetch the data from my API, who has 3 records, but I can only manage to bring only one (though index or not).

There's no problem with pagination or token, I just can't figure it out what's happening!

If I call .map() in console.log I receive the records just fine. Probably just calling the function in the wrong way ?

enter image description here

Payload from the API:

    {
    "count": 3,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 735,
            "title": "My GitHub",
            "description": "My Github",
            "url": "https://github.com/marrowsed",
            "category_name": "F"
        },
        {
            "id": 736,
            "title": "My Gmail",
            "description": "My Gmail",
            "url": "https://gmail.com",
            "category_name": "F"
        },
        {
            "id": 737,
            "title": "My Linkedin",
            "description": "My Linkedin",
            "url": "https://linkedin.com",
            "category_name": "F"
        }
    ]
}

React:

const Videos = () => {

  const [token, setToken] = useState(localStorage.getItem("token"))
  const [videos, setVideos] = useState([])

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

  let validateToken = async (token) => {
    let data = await config.validateToken(token)
    data.code === "token_not_valid" ? setToken(config.refreshToken(localStorage.getItem("refresh"))) : console.log("Valid Token")
  }

  let getAllVideos = async () => {
    if (validateToken(token)) {
      let response = await fetch(`${config.URL}videos/`,{
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
      }
      })
      let data = await response.json()
      return setVideos([data.results])
    } else {
      setToken(config.refreshToken(token))
    }
  }

  return (
    <>
    <h1>Videos</h1>
    <h3>Videos</h3>
    <div>
    {videos.flatMap(([v], index) => (
      <div key={index}>
        <h3>Title: {v.title}</h3>
        <p>Description: {v.description}</p>
        <p>URL: {v.url}</p>
        <p>Category: {v.category_name}</p>
        </div>  
    )
    )}
    </div>
    </>
  )
}

export default Videos

Appearing only one record:

enter image description here

The API is made with Django REST, pagination is 5 and Simple JWT. The record doesn't show if the token isn't valid, so I'm just lost

CodePudding user response:

Thanks to @pilchard in the comments, now its working!

...

    let getAllVideos = async () => {
    if (validateToken(token)) {
      let response = await fetch(`${config.URL}videos/`,{
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
      }
      })
      let data = await response.json()
      return setVideos(data.results)
    } else {
      setToken(config.refreshToken(token))
    }
  }

  return (
    <>
    <h1>Videos</h1>
    <h3>Videos</h3>
    <div>
    {videos.map(v => (
      <div key={v.id}>
        <h3>Title: {v.title}</h3>
        <p>Description: {v.description}</p>
        <p>URL: {v.url}</p>
        <p>Category: {v.category_name}</p>
        </div>  
    )
    )}
    </div>
    </>
  )
}
  • Related