-1

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;
Stainler
  • 61
  • 5
  • 1
    If you are using JSON data then you will need to parse it before setting it to the setItems state hook. When it is parsed you will be able to use it. – David Oct 26 '22 at 13:09
  • Can you provide more context? Could you share some sample data that you get from the api? – Ujwal Kumar Oct 26 '22 at 13:11
  • 1
    If the `fetch` resulted in something other than an array (i.e., `json` is an object or a primitive), this code will fail. Verify the data is what you expect it to be. – Heretic Monkey Oct 26 '22 at 13:13
  • Does this answer your question? [React | Items.map is not a function](https://stackoverflow.com/questions/55137072/react-items-map-is-not-a-function) – Heretic Monkey Oct 26 '22 at 13:14
  • Your issue is somewhere else, as you can see this works https://codesandbox.io/s/react-hooks-playground-forked-1ywllg?file=/src/index.tsx – P. Zietal Oct 26 '22 at 13:18
  • @David The OP is using the Fetch API, whose [`Response` object has a `json()` method that parses the JSON](https://developer.mozilla.org/en-US/docs/Web/API/Response/json), and the OP is using it correctly. – Heretic Monkey Oct 26 '22 at 13:23

1 Answers1

0

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;
Fralle
  • 889
  • 6
  • 12