Fares_Essayeh
Fares_Essayeh

Reputation: 105

fetching problems with react useEffect

i got this error fetching data just for practice i don't wanna use JSON.stringfy i don't think will be good practice, solve it with details please thank you

Error: Objects are not valid as a React child (found: object with keys {title, episode_id, opening_crawl, director, producer, release_date, characters, planets, starships, vehicles, species, created, edited, url}). If you meant to render a collection of children, use an array instead.

import { useState, useEffect, Fragment } from 'react';
import './App.css';

function App() {
  const [data, setData] = useState([]);
  useEffect(() => {
    const fetching = async () => {
      const response = await fetch('https://swapi.dev/api/films')
      const { results } = await response.json();
      const transformedData = results.map((el) => {
        return {
          id: el.episode_id,
          title: el.title,
          text: el.opening_crawl,
          date: el.releaseDate
        };
      });
      setData(transformedData);
    }
    fetching();
  })

  const outputedData = data.map((el) => {
    <div>
      <p>{el.id}</p>
      <p>{el.title}</p>
      <p>{el.text}</p>
      <p>{el.date}</p>
    </div>
  })

  return (
    <div className="App">
      {outputedData}
    </div>
  );
}

export default App;


console.log(results)

6) [{…}, {…}, {…}, {…}, {…}, {…}]0: {title: "A New Hope", episode_id: 4......}

Upvotes: 0

Views: 61

Answers (3)

tarzen chugh
tarzen chugh

Reputation: 11257

   <div className="App">
     {data.results.map((result) => {
       <span>{{result.title}}</span>
    })}
    </div>

Upvotes: 1

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

You must replace

const outputedData = data.map((el) => {
    <div>
      <p>{el.id}</p>
      <p>{el.title}</p>
      <p>{el.text}</p>
      <p>{el.date}</p>
    </div>
})

by

const outputedData = data.map((el) => (
    <div key={el.id}>
      <p>{el.id}</p>
      <p>{el.title}</p>
      <p>{el.text}</p>
      <p>{el.date}</p>
    </div>
))

Currently, your code doesn't return anything from the map function

Please note the use of the key attribute when displaying an array of React elements

Upvotes: 1

hspacheco
hspacheco

Reputation: 154

You cannot display an array of non-React elements. You need to do something like

return (
        <div className="App">
           {data.map(({title, episode_id, ...props}) => 
              <div>
                <span>{title}</span>
                <span>{episode_id}</span>
              </div>
           )}
        </div>
    );

Upvotes: 1

Related Questions