Last active
September 23, 2022 02:45
-
-
Save steven-tey/cce50c86764ab790da51c98e1a9b8a69 to your computer and use it in GitHub Desktop.
BlurImage Component that Self-Updates Twitter Profile Pics with the Twitter API
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
// components/BlurImage.js | |
import Image from 'next/image'; | |
import { useState, useEffect } from 'react'; | |
import cn from 'clsx'; | |
export default function BlurImage(props) { | |
const [isLoading, setLoading] = useState(true); | |
const [src, setSrc] = useState(props.src); | |
useEffect(() => setSrc(props.src), [props.src]); // update the `src` value when the `prop.src` value changes | |
return ( | |
<Image | |
{...props} | |
src={src} | |
alt={props.alt} // assuming `props.alt` is the user's Twitter username | |
className={cn( | |
props.className, | |
'duration-700 ease-in-out', | |
isLoading | |
? 'grayscale blur-2xl scale-110' // to create the blur loading effect | |
: 'grayscale-0 blur-0 scale-100', | |
)} | |
onLoadingComplete={async () => { | |
if (src.startsWith('https://abs.twimg.com/')) { | |
// try to update images that are the default Twitter profile pic | |
await updateTwitterDP(props.alt, setSrc); | |
} | |
setLoading(false); | |
}} | |
onError={async () => { | |
if ( | |
src.startsWith('https://abs.twimg.com/') || | |
src.startsWith('https://pbs.twimg.com/') | |
) { | |
await updateTwitterDP(props.alt, setSrc); | |
} | |
}} | |
/> | |
); | |
} | |
export async function updateTwitterDP(username, setSrc) { | |
const response = await fetch(`/api/update-dp?username=${username}`); | |
const data = await response.json(); | |
setSrc(data.src); | |
} |
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
// pages/api/update-dp.js | |
async function getLatestDP(username) { | |
const response = await fetch( | |
`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, | |
{ | |
method: 'GET', | |
headers: { | |
Authorization: `Bearer ${process.env.TWITTER_AUTH_TOKEN}`, | |
'Content-Type': 'application/json', | |
}, | |
}, | |
); | |
const data = await response.json(); | |
if (data.errors) { | |
// handle error here | |
} else { | |
return data.profile_image_url_https.replace('_normal', ''); | |
} | |
} | |
export default async function handler(req, res) { | |
const { username } = req.query; | |
const latestDP = await getLatestDP(username); | |
// update latestDP value in database | |
await db.user.update(...) | |
res.status(200).json({ src: latestDP }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment