dandrok
dandrok

Reputation: 27

react useEffect fetch - TypeError?

What is wront with this code..
on console everything work but after i try fetch data to div using setData(result) I have big fat error:

×
Unhandled Rejection (TypeError): setData is not a function
(anonymous function)
C:/blog/src/components/BlogPosts.js:19
  16 |        .then((res) => res.json())
  17 |        .then((result) => {
  18 |          console.log(result)
> 19 |          setData(result)
     | ^  20 |        })
  21 |    }
  22 | 
import { useState, useEffect } from 'react'
import styles from './BlogPosts.module.css'


const BlogPosts = () => {
  const { data, setData } = useState([])

  useEffect(() => {
    const fetchData = async () => {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then((res) => res.json())
        .then((result) => {
          console.log(result)
          setData(result)
        })
    }

    fetchData()
  }, [])

  return (
    <section className={styles.posts}>
      {/* <div>
        {data.map((x) => {
          return <div key={x.id}>{x.title}</div>
        })}
      </div> */}
    </section>
  )
}

export default BlogPosts

Upvotes: 0

Views: 299

Answers (2)

Suman Mondal
Suman Mondal

Reputation: 21

 const fetchData = async () => {
      let res = null;
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then((res) => res.json())
        .then((result) => {
          console.log(result)
          res = result;
        })
      return await res;
    }
useEffect(async() => {
   const data = await fetchData();
   setData(data);
  }, [])

Upvotes: 1

Areeb Khan
Areeb Khan

Reputation: 413

Here lies the problem:

  const { data, setData } = useState()

useState( ) hook returns an array so you should be destructuring an array instead

  const [ data, setData ] = useState()

P.S, doesn't hurt to initialise the state as an empty array (compared to nothing / undefined, which it is right now)

const [ data, setData ] = useState([])

You're doing this because down in the code you commented out, you're trying to use the map() method, which is a method of arrays.

Upvotes: 3

Related Questions