Skip to main content

part 4, fetch data with useEffect axios

--------------------------------------------------------------------------

 import React, { useState, useEffect } from 'react';

import axios from 'axios'

const DataPull = () => {

const [id, setId] = useState(1)
const [post, setPost] = useState({})
const [buttonid, setButtonid] = useState(1)

const handleClick = () => {
console.log("button id set")
setButtonid(id)
}

useEffect(() => {
console.log("normal id " + id)
console.log("button id " + buttonid)
axios.get(`https://jsonplaceholder.typicode.com/posts/${buttonid}`).then(res => {
setPost(res.data)
}).catch(err => {
console.log(err)
setPost({ title: "no data" })
})
}, [buttonid])



return (
<div>
<input type="text" value={id} onChange={e => { setId(e.target.value) }} />
<button onClick={handleClick}>Fetch</button>
<br />
{post.title}
</div>

);
}

export default DataPull;
//useEffect runs after every render of component




Comments

Popular posts from this blog

part 2 react hooks with objects and array

i mport React, { useState } from 'react'; import './App.css' const App = () => { const [name, setName] = useState({ fname: '', lname: '' }) return ( <div className="App"> <form> <input type="text" value={name.fname} onChange= {(e) => setName((prevstate) => ({ ...prevstate, fname: e.target.value }))} /> Fname is {name.fname} <br /> <input type="text" value={name.lname} onChange= {(e) => setName((prevstate) => ({ ...prevstate, lname: e.target.value }))} /> Lname is {name.lname} </form> { JSON . stringify ( name ) } </div> ); } export default App; onChange= {(e) => setName((prevstate) => ({ ...prevstate, lname: e.target.value }))} the ...prevstate above will merge current state to previous state #working with ARRAY import React , { useState } from 'react' ; import './App.css' const App = () => { const [ items , setItems ] =...

react hooks part 1

. import React , { useState } from 'react' ; import './App.css' const App = () => { const [ count1 , setCount1 ] = useState ( 1 ) const [ count2 , setCount2 ] = useState ( 2 ) const [{ count3 , count4 }, setCount ] = useState ({ count3 : 8 , count4 : 9 }) return ( <div className = "App" > <button onClick = { () => { setCount1 ( c => c + 1 ) setCount2 ( c => c + 1 ) } } > Add-it </button> <div> count1= { count1 } </div> <div> count2= { count2 } </div> <button onClick = { () => { setCount (( c ) => ({ ... c , count3 : count3 + 100 , count4 : count4 + 100 }) ) //here "c" is currentstate and the ...c spreadoperator } } > add obj </button> <div> count3= { count3 } </div><div> count4= { count4 } </div> </div> ); } export def...