Home > Enterprise >  item.map is not a function
item.map is not a function

Time:10-27

I am new to reactJS. i am expecting the json data to be fetched and displayed according to the options that are clicked. I tested with console.log and the data was being fetched correctly, however when i tried using useState setItems(json), it gives me an error of 'Uncaught TypeError: items.map is not a function'

import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { useState, useEffect} from 'react';

function App() {

  const [option, setOption] = useState('Posts')
  const [items, setItems] = useState([])

  useEffect(()=> {
    fetch(`https://jsonplaceholder.typicode.com/${option}`)
      .then(response => response.json())
      .then(json => setItems(json))
  }, [option])

  return (
    <div className="App">
      <div className='container'>
        <div className='menuBar'>
          <button onClick={()=> setOption('posts')}>Posts</button>
          <button onClick={()=> setOption('users')}>Users</button>
          <button onClick={() => setOption('comments')}>Comments</button>
          <h2>{option}</h2>
          {items.map(item => {
            return <pre>{JSON.stringify(item)}</pre>
          })}
        </div>
      </div>
    </div>
  );
}

export default App;

CodePudding user response:

To make your code fail-safe and easier to debug, you should check if items is an array before using map.

import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState, useEffect } from "react";

function App() {
  const [option, setOption] = useState("posts");
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/${option}`)
      .then(response => response.json())
      .then(json => setItems(json));
  }, [option]);

  return (
    <div className="App">
      <div className="container">
        <div className="menuBar">
          <button onClick={() => setOption("posts")}>Posts</button>
          <button onClick={() => setOption("users")}>Users</button>
          <button onClick={() => setOption("comments")}>Comments</button>
          <h2>{option}</h2>
          {Array.isArray(items) ? items.map(item => <pre>{JSON.stringify(item)}</pre>) : <pre>{JSON.stringify(items)}</pre>}
        </div>
      </div>
    </div>
  );
}

export default App;
  • Related