An Interest In:
Web News this Week
- March 1, 2024
- February 29, 2024
- February 28, 2024
- February 27, 2024
- February 26, 2024
- February 25, 2024
- February 24, 2024
June 6, 2019 06:31 pm GMT
Original Link: https://dev.to/joelnet/react-i-really-wish-this-is-how-i-could-write-components-1k4j
React: "I really wish this is how I could write components."
Challenge Accepted!
code for useMatchFetch
down below.
import React from "react";import { useMatchFetch } from "./effects/useMatchFetch";export const Example = () => { const render = useMatchFetch("https://swapi.co/api/people/1/?format=json"); return render({ pending: () => <div>Loading</div>, error: err => <div>{err.toString()}</div>, data: data => <pre>{JSON.stringify(data, null, 2)}</pre> });};
Watch my Live Stream
Want to see my process on how I created this? Watch me on Twitch!
useMatchFetch
I actually really like this. I think I might end up using this in a few places.
import { useState, useEffect } from "react";const render = data => match => data.pending ? match.pending() : data.error ? match.error(data.error) : data.data ? match.data(data.data) : null // prettier-ignoreexport const useMatchFetch = url => { const [data, setData] = useState({ pending: true }); useEffect(() => { fetch(url) .then(response => response.json()) .then(data => setData({ data, pending: false })) .catch(error => setData({ error, pending: false })); }, [url]); return render(data);};
End
Follow me on Twitter @joelnet
Original Link: https://dev.to/joelnet/react-i-really-wish-this-is-how-i-could-write-components-1k4j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To