Category Archives: General

How to make an API call that streams data

Using fetch

const response = await fetch("/endpoint", {
  signal: AbortSignal.timeout(10000),
});

const reader = response.body.getReader();

while (true) {
  const { done, value } = await reader.read();

  if (done) {
    console.log("Stream complete");
    break;
  }

  console.log(new TextDecoder().decode(value));
}

XHR

var xhr = new XMLHttpRequest();
xhr.open('GET', '/endpoint', true);
xhr.timeout = 10000;
xhr.ontimeout = function() {
  console.error('Request timed out!');
};
xhr.onprogress = function() {
  var responseText = xhr.responseText;
  var chunk = responseText.slice(xhr.prevLen);
  xhr.prevLen = responseText.length;
  console.log(chunk);
};
xhr.onload = function() {
  console.log('Done!');
};
xhr.send();

Axios:

Not supported. Said to be impossible in 2009, closed in 2016, and there's still no support for it today.

General API:

async function GET(req, res) {
  res.write('hello')
  await new Promise((resolve) => setTimeout(resolve, 1000))
  res.write('world')
  res.end()
}

Optional: Next.js 14 endpoint:

import { NextApiResponse } from 'next'

// https://developer.mozilla.org/docs/Web/API/ReadableStream#convert_async_iterator_to_stream
function iteratorToStream(iterator: any) {
  return new ReadableStream({
    async pull(controller) {
      const { value, done } = await iterator.next()

      if (done) {
        controller.close()
      } else {
        controller.enqueue(value)
      }
    },
  })
}

function sleep(time: number) {
  return new Promise((resolve) => {
    setTimeout(resolve, time)
  })
}

const encoder = new TextEncoder()

async function* makeIterator() {
  yield encoder.encode('<p>One</p>')
  await sleep(700)
  yield encoder.encode('<p>Two</p>')
  await sleep(700)
  yield encoder.encode('<p>Three</p>')
}

export default async function handler(req, res: NextApiResponse<any>) {
  const iterator = makeIterator()
  const stream = iteratorToStream(iterator)

  return new Response(stream)
}

export const runtime = 'edge'

How to make a Nextron App with API routes even in production/bundled mode

import dotenv from 'dotenv'
import { BrowserWindow, app, ipcMain } from 'electron'
import log from 'electron-log/main'
import * as http from 'http'
import * as net from 'net'
import next from 'next'
import path from 'path'
import { parse } from 'url'

const logger = log.scope('main')

const load = async () => {
  await app.whenReady()

  logger.info('App ready')

  const rendererPath = path.join(app.getAppPath(), 'renderer')
  const nextApp = next({ dev: !isProd, dir: rendererPath })
  const handle = nextApp.getRequestHandler()

  await nextApp.prepare()

  server = http.createServer((req: any, res: any) => {
    logger.info(`HTTP Request [${req.method}] ${req.url}`)
    const parsedUrl = parse(req.url, true)

    handle(req, res, parsedUrl)
  })

  const serverPort = await new Promise((resolve) => {
    server.listen(0, () => {
      const address = server.address() as net.AddressInfo
      logger.info(`  >> Ready on http://localhost:${address.port}`)
      logger.info(`Renderer path: ${rendererPath}`)

      resolve((server.address() as net.AddressInfo).port)
    })
  })

  global.baseUrl = `http://localhost:${serverPort}`
  global.port = serverPort
  process.env.NEXTAUTH_URL = global.baseUrl

  const mainWindow = await createMainWindow({
    url: global.baseUrl,
    isProd,
    allAppWindows,
    appInfo: {
      baseUrl: global.baseUrl,
      port: global.port,
    },
  })

  // do not use dev port or app://
  // use your server instead
  await mainWindowawait mainWindow.loadURL(`${global.baseUrl}/home`)
}

logger.info('Loading app...')
load()

How to build a perfect resume on LinkedIn (for Developers by Developers)

Going through your profile, from top to bottom.

Photo and Banner

Make it interesting.

  • You’ll be more likely to be remembered.
  • They’ll be more likely to get out of autopilot and pay attention.

Contact Information

Make it as easy as possible for people to reach out. Add your email address, phone number, and/or any other easy direct channel.

It’s nice to have links to your Stack Overflow, GitHub, Blog, Website, etc. Even if they don’t open it, they’ll be aware you have those and that’s a plus.

Headline

Recruiters will see your headline while scrolling through hundreds/thousands of candidates. If your headline doesn’t include something in their list of keywords, you’ll be missed. You can be creative, but make sure to include a common keyword on your headline.

Common keywords: Developer / Full Stack Developer (Engineer) / Software Developer (Engineer)

Recruiters could potentially also be using the keyword “Senior”, so you might want to prefix your title with it in some cases.

About

Make it clear what you like to work with, what you want to work with, your overall experience, your biggest projects/accomplishments. Put the most essential information first so it doesn’t get hidden by the “read more” feature.

If you have any big projects, accomplishments, something that will catch others attention put it in here.

Experience

Make sure to include the programming languages / technology you worked with. You can also show numbers (e.g. my app had 1M users; it increased revenue in 50%; etc). You can describe what was your role on the things you worked on.

You can use fancy and different titles as long as you include the most used keywords in them as well (e.g. Creative person 123 | Full Stack Developer). Automated tools and sometimes people will not count your experience as something valid and you might not be included in lists and such.

Skills & Endorsements

Make sure your Top 3 are extremely relevant. For example, if you want to work as a Full Stack JavaScript developer you probably want to put your top 3 as JavaScript, React, Node.

Complete the list with other relevant skills.

Take the skill assessments to get a badge “proving” you know your stuff.

Recommendations

Ask your co-workers / friends for recommendations. Having 3 is enough as it is the limit shown on the main page.

Languages

Make sure you put the languages you can speak in there, you could easily be discarded for a position that requires you to speak in English if you don’t have it in there, even if your entire resume is in English.

Education

This is up to you to put it in here or not. Ask yourself first: do you want to work for a company that values this?

Other

  • Open to work over your photo: generally bad, you’ll be seen as junior

Questions? Reach out to me: https://www.linkedin.com/in/brunolm/

Random image to make it cool to share:

How to use two-way binding in Nullstack

Nullstack is a feature-driven full stack JavaScript framework that helps you build isomorphic applications and stay focused on shipping products to production. One of the features that makes Nullstack stand out is its support for two-way binding between your component state and the DOM.

Two-way binding means that any changes made to your component state will be automatically reflected in the DOM, and vice versa. This makes it easy to create interactive UIs without having to manually update the DOM or listen for events.

In this post, I will show you how to use two-way binding in Nullstack with some examples.

How to bind a variable to an input element

One of the most common use cases for two-way binding is to bind a variable to an input element, such as a text field or a checkbox. To do this, you just need to use the bind attribute on the input element and assign it the name of your variable.

For example, let’s say we have a component called Form that has a variable called name. We want to bind this variable to an input element so that we can get the user’s name. Here is how we can do it:

class Form extends Nullstack {
  // variables are just variables
  name = '';

  render() {
    return (
      <form>
        {/* two way bindings */}
        <input bind={this.name} />
      </form>
    );
  }
}

Now, whenever we type something in the input element, it will update the value of this.name in our component state. And whenever we change the value of this.name programmatically, it will update the value of the input element in the DOM.

How to bind an object property to an input element

Sometimes, we may want to bind an object property instead of a simple variable. For example, let’s say we have a component called Profile that has an object called user with properties like nameemail, and age. We want to bind these properties to different input elements so that we can edit them.

To do this, we just need to use dot notation on the bind attribute and assign it the path of our object property.

For example:

class Profile extends Nullstack {
  // objects are just objects
  user = {
    name: 'Nulla',
    email: 'nulla@nullstack.app',
    age: 21,
  };

  render() {
    return (
      <form>
        {/* two way bindings with dot notation */}
        <input bind={this.user.name} />
        <input type="email" bind={this.user.email} />
        <input type="number" bind={this.user.age} />
      </form>
    );
  }
}

Now, whenever we change any of these input elements, it will update the corresponding property of this.user in our component state. And whenever we change any property of this.user programmatically, it will update the corresponding input element in the DOM.

How to bind an array item or index

Another common use case for two way binding is to bind an array item or index. For example, let’s say we have a component called TodoList that has an array called todos with items like { text: 'Learn Nullstack', done: false }. We want to bind these items or their indexes to different elements so that we can display them and toggle their status.

To do this, we just need to use bracket notation on the bind attribute and assign it either an array item or its index.

For example:

class TodoList extends Nullstack {
  // arrays are just arrays
  todos = [
    { text: 'Learn Nullstack', done: false },
    { text: 'Build awesome apps', done: false },
    { text: 'Have fun', done: true },
  ];

  render() {
    return (
      <ul>
        {/* loop through todos */}
        {this.todos.map((todo) => (
          <li>
            {/* two way bindings with bracket notation */}
            <input type="checkbox" bind={todo.done} />
            <span>{todo.text}</span>
          </li>
        ))}
      </ul>
    );
  }
}

Now, whenever we check or uncheck any of these checkboxes, it will

update the corresponding property of todo.done in our component state. And whenever we change any property of todo.done programmatically, it will update the corresponding checkbox in the DOM.

Conclusion

In this post, I showed you how to use two-way binding in Nullstack with some examples. Two-way binding is a powerful feature that makes it easy to create interactive UIs without having to manually update the DOM or listen for events. It also reduces the amount of glue code you must write in your application.

If you want to learn more about Nullstack, you can check out its official website, documentation, or GitHub repository. You can also join its Discord community if you have any questions or feedback.

I hope you enjoyed this post and learned something new. Happy coding!

What is Nullstack and why should React developers migrate to it?

Nullstack is a feature-driven full stack JavaScript framework that helps you build isomorphic applications and stay focused on shipping products to production. It connects a UI layer with state management to microservices in the same component using pure JavaScript classes. You write the backend and frontend of a feature in a single isomorphic component and let the framework decide where the code should run.

If you are a React developer, you might be wondering what are the benefits of migrating to Nullstack. Here are some reasons why you should consider it:

  • No more glue code: You don’t need to create APIs manually or use third-party libraries for data fetching, routing, authentication, etc. Nullstack handles all these aspects for you automatically. You write features for products, not glue code for frameworks.
  • Optimized for performance: Nullstack delivers SEO-ready HTML optimized for the first render of your route in a single request using local functions with zero JavaScript dependencies in the client bundle. After that, it becomes a single page application (SPA) that fetches JSON from an automatically generated microservice API and updates the application state and DOM accordingly. You get fast SSR and offline PWA out of the box.
  • Easy to read and write: Nullstack components are just plain old JavaScript objects (POJOs). You can use JavaScript or TypeScript as it is supposed to be, without any special syntax or boilerplate. JSX tags follow the HTML standard, routes are simple attributes you can assign to any tag, and links are just anchor tags. You already know Nullstack if you know HTML and JavaScript.
  • DX with batteries included: Nullstack has a lot of out of the box shortcuts that were extracted out of repeating patterns in real projects instead of architecture books. For example, you can use two-way bindings, object events, context variables, hooks, plugins, etc. without any extra configuration or installation.
  • TypeScript: Nullstack supports TypeScript natively. You can use it by renaming your `.njs` or `.jsx` files to `.nts` or `.tsx` respectively. Nullstack will compile them with Babel and preserve the types for your editor or IDE. You can use it by adding -ts or --typescript flag when creating a new project with npx create-nullstack-app.
  • Tailwind: Nullstack supports Tailwind natively. You can use it by adding -tw or --tailwind flag when creating a new project with npx create-nullstack-app. This will generate a project template with Tailwind already configured.

Nullstack is not just another framework; it’s a new way of thinking about web development that focuses on features instead of layers. It’s designed to make your life easier as a developer and your users happier as customers.

People are trying to do it, but Nullstack already did 😎

AI already knows about Nullstack, better than any of us probably!

import { Nullstack } from 'nullstack';

class WaifuList extends Nullstack {

  waifus = [];

  async initiate() {
    this.waifus = await this.getWaifus();
  }

  static async getWaifus({ database }) {
    return database.query("SELECT * FROM WAIFUS");
  }

  render() {
    return (
      <div>
        <h1>My Waifus</h1>
        <ul>
          {this.waifus.map(waifu => (
            <li>{waifu.name}</li>
          ))}
        </ul>
      </div>
    );
  }
}

If you want to learn more about Nullstack or try it out yourself, visit https://nullstack.app/ or follow them on Twitter @nullstackapp.

Path to become a God – JavaScript

https://workflowy.com/s/path-to-become-a-god/HtEy7i3Fig0vFy4o

Golden rules

  • NEVER take for granted what you see on guides/courses.
    • They might contain subjective opinions that might not be the best approach
    • They might be flawed
    • They might be outdated
    • You should cross reference. Check something you learned in multiple places and see if all of them are doing it the same way, or if that’s a very personal opinion from someone.
  • Learn how to get things done, and then learn how to make things right
    • Get started, make things happen, you can worry about best practices later.
    • CodeWars will help you do that; you’ll learn the best way to do things with other very skilled developers.

Read the full path at:

https://workflowy.com/s/path-to-become-a-god/HtEy7i3Fig0vFy4o

Looking for a job as a Full Stack Developer – JavaScript? US/BR

https://www.linkedin.com/posts/brunolm_hiring-fullstack-blockchain-activity-6874813652688486401-Vb1X

HEY YOU, the end of the year is coming, would you like to start fresh and:
🤗 work in a place where you feel valued?
🌎 work remotely?
🧑‍🔬 work to improve Human Agency and make the world a better place?
🧑‍🤝‍🧑 work in a collaborative environment?
💻 work with top-tier developers, in a top-rated company on Clutch?

WE’RE HIRING! JOIN US!
✅ https://buff.ly/3eBpCOX
💻 Full Stack Developers / Tech Leads
🎨 Product Designers
🔗 Blockchain Developers
🧪 Data Scientists

No alternative text description for this image

TypeScript Everything

All JavaScript is TypeScript. If you have been coding in JavaScript you already know how to code in TypeScript.

Any new features coming to JavaScript will be supported by TypeScript as long as the features make into Stage 3, which is like the “Release Candidate”, so you’re going to get access to features before they’re released.

Continue reading