Snippets
React
How do we create a closure in JavaScript?
function createCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const counter = createCounter();
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
The inner function has a closure (or backpack) that allows it to "remember" the value of count no matter where we call it!
This is a super powerful tool that makes a lot of things possible!
Closures in React
Here's the "React" version of the above code
export function Counter() {
const [count, setCount] = useState(0);
function updateCount() {
setCount(count + 1);
}
return <button onClick={updateCount}>{count}</button>;
}
Ok but I'm kind of lost here. I forked this portfolio from reilly.dev (opens in a new tab) and he forked the Nextra (opens in a new tab) template for Next.js.
In that repo was this post, which I haven't deleted (which is gone from his site by the way), about closures, which I grok pretty easily now. But reasoning about this in React might take some time!
JSON as a data structure
I was working on the projects portion of this site that I forked from ibelick (opens in a new tab) and I thought that I could extract the array of project objects into a little lib file projects.ts
, create a component and add that component directly into MDX:
const PROJECTS_LIST = [
{
title: "some project",
description:
"Ideal burying fearful faithful chaos endless value merciful ideal endless good overcome deceptions contradict. Grandeur will spirit ocean endless good.",
links: {
text: "Website",
link: "https://example.com",
},
tags: ["React", "Tailwind CSS", "TypeScript", "2023", "Open source", "UI"],
emoji: "💫",
video: {
link: "https://www.youtube.com/watch?v=jIQ6UV2onyI&pp=ygURbnlhbiBjYXQgMTAgaG91cnM%3D",
width: "w-full",
height: "h-80",
},
},
// ...
];
export default PROJECTS_LIST;
Then I could do something like:
function Portfolio() {
return (
<div className="flex flex-col items-center justify-center w-full">
<div className="flex flex-col items-center justify-center w-full">
<h1 className="text-4xl font-bold text-center text-gray-900">
Projects
</h1>
<p className="mt-2 text-lg text-center text-gray-600">
Here are some of the projects I've worked on.
</p>
</div>
<div className="flex flex-col items-center justify-center w-full">
<ProjectList projects={PROJECTS_LIST} />
</div>
</div>
);
};
Make sense? It's now inside my projects page as a reusable component.
Python
Here is a snippet from a Python project I am working on where I want to create a new RSS feed on the command line. It's been in the works for almost a year now, sadly...
#!/usr/bin/env python
# coding=utf8
import feedparser
import typer
from typing import Optional
import sys
import datetime
import urllib
import pprint
import datetime
import json
# We'll need to instantiate the Typer class so we can
# work with it later when we need to get input
# from the command line
app = typer.Typer()
# Here I created a function where I pass a default parameter
# and assign that parameter to the app variable I created above the function
# I have not run this yet so not sure of any scope issues
def main(url: str = typer.Option(...,prompt="Please enter the url you'd like to parse")):
"""
This is where I'll place morst of
the business logic for this script
"""
app.echo(f"{url}")
fp = feedparser.parse(url)
fp['feed']['title']
print(fp)
if __name__ == "__main__":
main()
Ruby
Here, I am experimenting with FileUtils
and File
in Ruby. I am trying to create a new file and write to it. I am also trying to create a new directory and write to a file in that directory.
require 'fileutils'
path = File.expand_path('../', __FILE__)
Dir.glob("#{path}/**/*.*").each do |file|
new_path = "#{path}/#{file.split('/')[-1]}"
FileUtils.mv(file, new_path)
end
This is for my static site generator that is also been in the works for over two years...
I truly need some help with this (opens in a new tab) project (opens in a new tab) so if you can take a look that would be helpful!