Skip to main content

Command Palette

Search for a command to run...

Simple React useState hook example?

Published
1 min read
Simple React useState hook example?
S

I love learning about technology and sharing that with others

Introduction

here we are again with the simplest useState example where when ever the state is changed we are calling an API storing the details to a different state and displaying it

import React, { useState, useEffect } from 'react'
import { ClipboardCheck } from 'react-bootstrap-icons'

//whenever we wants to mounts a component or unmount based on any change to the state
// we will be using the useState component.

const First = () => {
  const [resourceType, setResourceType] = useState('posts')
  const [message, setMessage] = useState([])

  const fetchData = () => {
    fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
      .then((response) => response.json())
      .then((json) => {
        setMessage(json)
      })
  }

  useEffect(() => {
    fetchData()
  }, [resourceType])
  return (
    <div>
      <button onClick={() => setResourceType('posts')}>Posts</button>
      <button onClick={() => setResourceType('users')}>Users</button>
      <button onClick={() => setResourceType('comments')}>Comments</button>

      <div>
        <h2>
          {message.map((item) => (
            <h6>{JSON.stringify(item)}</h6>
          ))}
        </h2>
      </div>
    </div>
  )
}

export default First
17 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)