Pull to refresh
150.03

JavaScript *

High-level, interpreted programming language. It is a language which is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm

Show first
Rating limit

polluSensWeb now supports 26 sensors and webhooks

polluSensWeb
polluSensWeb

With the latest updates, polluSensWeb now supports 26 different sensors and introduces webhook integration, opening up possibilities for real-time automation, data forwarding, and external analytics pipelines.

These sensors are manufactured by different companies and use different protocols. Some transmit data continuously, while others require start commands.

Until now, polluSensWeb was primarily a visualization and diagnostic tool. The data remained within the browser session. This was convenient for testing, calibration, or demonstration, but it limited real-world use cases.

With webhooks enabled, sensor data can be automatically sent to an external endpoint in real time.
This makes it possible to:

  • Forward measurements to databases

  • Trigger alerts or automation workflows

  • Send data to monitoring dashboards such as Grafana

  • Integrate with community platforms or custom APIs

Project on GitHub
Live deployment
Project on GitHub

Tags:
0
Comments0

Based on the heated discussions and criticism regarding the slow code and poor FPS in the test for displaying the sin()+noise graph using Python Matplotlib, improvements were made, and AI was employed to refine the code. The original article and code have undergone the following enhancements:

  • Abandoning the slow text output.

  • Utilizing FuncAnimation instead of a simple loop.

  • Implementing the magic command to connect the PyQT backend

As a result, the FPS increased from 12 to 100. For more details, 

please refer to the original article. https://habr.com/ru/articles/878002/

Tags:
Total votes 1: ↑1 and ↓0+2
Comments0

Заголовок: Я переписал react-query | Легковесный хук для асинхронного получения данных и кэширования в React

Привет всем!

Я разработал легковесный React-хук, аналогичный React Query, с основными функциями: получение данных, кэширование, повторные попытки и др. Он компактнее и проще в настройке. Полный код доступен на GitHub и в npm как api-refetch.

Зачем создавать собственный хук?

  1. Легковесность: React Query и SWR мощные, но крупные. Мой хук идеален, когда важен размер пакета, особенно для зависимостей вроде Intlayer.

  2. Настройка и оптимизация: Возможность хранения данных в локальном хранилище и управления параллельными запросами. Копируя или клонируя код, можно удалить ненужные функции, уменьшив размер бандла и повысив производительность.

  3. Без провайдера: Избегаю использования Context Provider для глобального доступа, предлагая версию на базе Zustand.

  4. Учебное упражнение: Понимание внутренностей кэширования и управления состоянием.

Создание собственного хука позволило сосредоточиться на нужных функциях, сохраняя библиотеку маленькой и понятной.

Функции

  • Получение данных и управление состоянием: Загрузка, ошибки, успешные данные.

  • Кэширование и хранение: Через React или Zustand, поддержка локального хранилища.

  • Повторные попытки и валидация: Настраиваемые лимиты и интервалы.

  • Активация и инвалидизация: Управление запросами в зависимости от других данных.

  • Параллельные запросы: Предотвращение дублирования запросов при монтировании нескольких компонентов.

Пример использования

Установка

Клонируйте репозиторий или установите через npm:

npm install api-refetch

Быстрый пример

import { AsyncStateProvider, useAsync } from "api-refetch";

function App() {
  return (
    <AsyncStateProvider>
      <UserDetails />
    </AsyncStateProvider>
  );
}

const fetchUserData = async () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: "John Doe" });
    }, 1000);
  });
};

const UserDetails = () => {
  const { isLoading, data, error, revalidate } = useAsync(
    "userDetails",
    fetchUserData,
    {
      enable: true,
      cache: true,
      store: true,
      retryLimit: 3,
      retryTime: 10000,
      autoFetch: true,
      revalidation: true,
      revalidateTime: 300000,
      onSuccess: (data) => console.log("Данные получены:", data),
      onError: (error) => console.error("Ошибка:", error),
    }
  );

  if (isLoading) return <div>Загрузка...</div>;
  if (error) return <div>Ошибка: {error}</div>;
  return (
    <div>
      <h1>{data?.name}</h1>
      <button onClick={revalidate}>Обновить</button>
    </div>
  );
};

Попробуйте api-refetch, сообщите об ошибках или внесите вклад. Обратная связь приветствуется!

GitHub: api-refetch

Счастливого кодинга!

Tags:
Total votes 1: ↑1 and ↓0+1
Comments2
Tags:
Total votes 8: ↑7 and ↓1+6
Comments0

Authors' contribution