Separating view and logic
import React from "react"
import { useAsync } from "react-async"
const fetchPerson = async ({ id }, { signal }) => {
const response = await fetch(`https://swapi.co/api/people/${id}/`, { signal })
if (!response.ok) throw new Error(response.statusText)
return response.json()
}
const Person = ({ id }) => {
const state = useAsync({ promiseFn: fetchPerson, id })
return children(state)
}
const App = () => {
return (
<Person id={1}>
{({ isPending, data, error }) => {
if (isPending) return "Loading..."
if (error) return <ErrorMessage {...error} />
if (data) return <Greeting {...data} />
return null
}}
</Person>
)
}Cleaning up the JSX
Last updated
Was this helpful?