DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

React Interview Question

Create a React web application that consumes the https://swapi.dev/api/people/ API and displays a table containing a list of Star Wars characters and the films they have appeared in and the vehicles they have used. The application should make multiple parallel API calls to fetch the film and vehicle details using the URLs returned in the first API call and display them in the table.

Publicis sapient

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

function App() {
  // Install axios using: npm install axios
  const [characters, setCharacters] = useState([])

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch Star Wars characters
        const response = await axios.get('https://swapi.dev/api/people/')
        const charactersData = response.data.results

        // Create an array of promises for fetching film and vehicle details
        const promises = charactersData.map(async (character) => {
          const filmsPromise = Promise.all(
            character.films.map((film) => axios.get(film)),
          )

          const vehiclesPromise = Promise.all(
            character.vehicles.map((vehicle) => axios.get(vehicle)),
          )

          const [filmsResponse, vehiclesResponse] = await Promise.all([
            filmsPromise,
            vehiclesPromise,
          ])

          const filmsData = filmsResponse.map((film) => film.data.title)
          const vehiclesData = vehiclesResponse.map(
            (vehicle) => vehicle.data.name,
          )

          return {
            ...character,
            films: filmsData,
            vehicles: vehiclesData,
          }
        })

        // Wait for all promises to resolve
        const charactersWithDetails = await Promise.all(promises)

        setCharacters(charactersWithDetails)
      } catch (error) {
        console.error('Error fetching data:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div>
      <h1>Star Wars Characters</h1>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Films</th>
            <th>Vehicles</th>
          </tr>
        </thead>
        <tbody>
          {characters.map((character) => (
            <tr key={character.name}>
              <td>{character.name}</td>
              <td>{character.films.join(', ')}</td>
              <td>{character.vehicles.join(', ')}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sidharrth profile image
Siv Deploys

As is code Compile Issues:
(node:11024) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use node --trace-deprecation ... to show where the warning was created)
(node:11024) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

As is Code Run issues
react-dom.development.js:86 Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

'ReactDOM' is defined but never used no-unused-vars

One of your dependencies, babel-preset-react-app, is importing the "@babel/plugin-proposal-private-property-in-object" package without declaring it in its dependencies. This is currently working because "@babel/plugin-proposal-private-property-in-object" is already in yournode_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which is not maintained anymore. It is thus unlikely that this bug will ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to your devDependencies to work around this error. This will make this message go away.