Home > Back-end >  React App: Need advise on mapping json data into table
React App: Need advise on mapping json data into table

Time:10-05

I have to fetch data from an api and map it to table. This is my code. Would anyone please advise the map function? Thank you.

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

const MovieList = () => {

    const [movies, setMovies] = useState([]);
    useEffect(() => {
    const fetchItems = async () => {
      const result = await axios(
        `api endpoint url`
      )
      setMovies(result.data)
    }
    fetchItems()
  }, [])
    
  return (
    #omit codes for table heads 
          <tbody>
          {movies.map(movie => (
            <tr>
                <td>{movie.results.year}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
                <td>{}</td>
            </tr>
            ))}
          </tbody>
}
export default MovieList;

enter image description here

enter image description here

CodePudding user response:

Update movies as

setMovies(result.data.results)

Then instead of

movies.map()

use

movies[0].films.map(movie => {})

CodePudding user response:

Seems you have a response that is result is an array of films (another array) in each year. So, the ugly way is just iterate carefully through these arrays, e.g:


      {movies.map((movie: any) => {
        movie.results.map((yearData: any) => (
          <tr>
            <td>{yearData.year}</td>
            {yearData.films.map((film: any) => (
              <Fragment>
                <td>{film['Detail URL']}</td>
                <td>{film.Film}</td>
                <td>{film['Producer(s)']}</td>
                <td>{...etc}</td>
              </Fragment>
            ))}
          </tr>
        ));
      })}

But if you can make the response better in backend, I suggest you to respond the films grouped by year, that would make everything easier. For example:

[
  { 
    year: '2021',
    films: [{...}]
  },
  { 
    year: '1973',
    films: [{...}]
  },
  { 
    year: '1927 / 28 [A] (1st)',
    films: [{...}]
  },
  ...
]

  • Related