Created
March 5, 2020 20:55
-
-
Save danielschmitz/f22be17994bca9a41434223b16017a83 to your computer and use it in GitHub Desktop.
React Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useState} from 'react'; | |
export default function App() { | |
/** | |
* States | |
*/ | |
const [_reps, setReps] = useState([]); | |
/** | |
* Effects | |
*/ | |
useEffect( () => { | |
async function fetchData() { | |
const response = await fetch('https://api.github.com/users/danielschmitz/repos'); | |
setReps(await response.json()); | |
} | |
fetchData(); | |
}, []) | |
useEffect( () => { | |
const quantosfavoritos = _reps.filter(rep => rep.favorite).length | |
document.title = `Você tem ${quantosfavoritos} favorito${quantosfavoritos===1?'':'s'}` | |
}, [_reps]) | |
/** | |
* Handlers | |
*/ | |
const handleFavButtonCLick = id => { | |
console.log('fav', id); | |
const newReps = _reps.map ( rep => { | |
return rep.id === id ? {...rep, favorite: !rep.favorite} : rep | |
}) | |
setReps(newReps) | |
} | |
/** | |
* Components | |
*/ | |
const cIsFav = rep => ( | |
rep.favorite && '(F)' | |
) | |
const cFavButton = id => ( | |
<button onClick={() => handleFavButtonCLick(id)}>Fav {id}</button> | |
) | |
const cListagem = _reps.map(rep => { | |
return <li key={rep.id}>{rep.name} {cIsFav(rep)} {cFavButton(rep.id)}</li> | |
}); | |
/** | |
* Main Component | |
*/ | |
return ( | |
<> | |
<h1>Hello World</h1> | |
<ul>{cListagem}</ul> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment