Skip to content

Instantly share code, notes, and snippets.

@erockdotdev
Created January 10, 2020 20:48
Show Gist options
  • Save erockdotdev/3c41dcd874af6995bafdba610c911fcd to your computer and use it in GitHub Desktop.
Save erockdotdev/3c41dcd874af6995bafdba610c911fcd to your computer and use it in GitHub Desktop.
scrappy react hooks example with useState, useEffect and fetch
import React, { useState, useEffect } from "react";
function App() {
// implied setState in second param
const [buttonText, setButtonText] = useState("What is This?");
const [input, updateInput] = useState("placeholder");
const [swapiData, setData] = useState();
useEffect(() => {
const url = "https://swapi.co/api/people/1/";
fetch(url)
.then(res => res.json())
.then(data => setData(data))
.catch(error => console.error("Error", error));
}, []);
// function handelClick() {
// return setButtonText("I guess i get this?");
// }
function handleInputChange(e) {
const { value } = e.target;
updateInput(value);
}
console.log("swapiData", swapiData);
return (
<div className="App" style={{ border: "solid red 5px", height: "200px" }}>
<button>{buttonText}</button>
<div style={{ border: "solid black 5px" }}>
<input
placeholder="placeholder"
onChange={e => {
handleInputChange(e);
}}
/>
<h1>{input}</h1>
<h3>{swapiData && swapiData.name}</h3>
</div>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment