Syed Talal Jilani
Syed Talal Jilani

Reputation: 13

how to display post title of json placeholder api in react

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([]);
    useEffect(()=>{
        fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.json())
    .then((json) => setPosts(json));
    },[])
    return(
        <div>
            <ul>
                {
                    posts.map(post => {
                        return<li key={post.id}>{post.title}</li>
                    })
                }
            </ul>
        </div>
    );
 
}

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> 
            <div className={styles.navbar__right}>
                <button className={styles.Btn} onClick={GetData}>Get Data</button>
            </div>           
        </div>

     </div>
    );
}

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.

Upvotes: 0

Views: 194

Answers (1)

Bl1xvan
Bl1xvan

Reputation: 35

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

useState([{}])

Upvotes: 1

Related Questions