[SOLVED] how to display post title of json placeholder api in react


This Content is from Stack Overflow. Question asked by Syed Talal Jilani

I want to create a navbar with button when user click on button data fetch from api and display using list
code of getdata component

import {useState,useEffect} from 'react'
export function GetData()
   const [posts , setPosts] = useState([]);
    .then((response) => response.json())
    .then((json) => setPosts(json));
                    posts.map(post => {
                        return<li key={post.id}>{post.title}</li>

code of navbar component

import styles from './NavbarStyle.module.css';
import {GetData} from './GetData'

export const Navbar = () => {
    return (
     <div className={styles.container}>
           <div className={styles.navbar}>
            <div className={styles.navbar__left}>
              <p className={styles.Logo}>API PROJECT</p>
            <div className={styles.navbar__right}>
                <button className={styles.Btn} onClick={GetData}>Get Data</button>


and error is Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.


When I look at the jsonplaceholder api, I don’t see an array. Just a single object. Mapping would work for an array with at least one object inside of it. And the initial useState would be an empty array with an empty object inside of it, like this


This Question was asked in StackOverflow by Syed Talal Jilani and Answered by Bl1xvan It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?