Created
September 17, 2020 07:33
-
-
Save RobMacKay/c6f13cf664d45dc4ad0293d1368417a4 to your computer and use it in GitHub Desktop.
Example Stateful Functional Component React.
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 Example(props) { | |
// you don't have to call these state and setState. | |
const [state, setState] = useState([state]) | |
// Think of this as ComponentDidMount | |
useEffect(() => { | |
// You can put all javascript in here like "componentDidMount" | |
// You can check and update state here too - simple fetch example: | |
let url = "https://myrest.com/api/endpoint" | |
fetch(url) | |
.then(res => res.json()) | |
.then(res => setState(res)) | |
.catch(error => console.log(error)) | |
}, [state]) // this is to "check for changes" - otherwise useEffect will loop and you will be confused. | |
return ( | |
<div> | |
{state.title} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment