Table of Contents
React Rock

React Rock

Jan 03, 2025 pm 10:55 PM

React Rock

React Rock

React-Rock is a lightweight package for managing global state in React applications. It simplifies handling data by providing a store with rows and metadata, while offering methods to perform CRUD operations and more. It enables easy integration with React components, making it an ideal solution for managing complex state in large applications.

Installation

To install the React-Rock package, run the following command in your project:

npm install react-rock
Copy after login
Copy after login
Copy after login

Features

  • Global Store Management: Manage rows and meta data in a global store.
  • CRUD Operations: Perform create, read, update, and delete operations on rows.
  • Meta Management: Set, get, and delete meta data.
  • Optimized Re-renders: Control component re-renders with the freeze option.
  • Class Component Support: Use the StoreComponent for integrating store data into class components.

Basic Example: Creating a Store and Adding Records

To create a new store and add a record, use the createStore function. Here's an example:

import { createStore } from 'react-rock';

// Define RowType and MetaType
type RowType = { name: string, age: number };
type MetaType = { totalRecords: number };

// Create a store
const users = createStore<RowType, MetaType>({ name: '', age: 0 }, { totalRecords: 0 });

// Add a new row to the store
users.create({ name: 'John Doe', age: 30 });
Copy after login
Copy after login
Copy after login

RowType Explained

When a row is created, it will have the following properties:

type RowType<Row> = Row & {
    _id: string;       // Unique identifier for the row
    _index: number;    // Index of the row in the store
    _observe: number;  // Internal property to track changes
}
Copy after login
Copy after login

Each row will include the original data (Row) and some additional properties like _id, _index, and _observe.

Methods

Here’s a table with all available methods and their descriptions:

Method Description
create(row, freeze?) Adds a new record to the store. Optionally, prevents re-rendering if freeze is true.
createMany(rows, freeze?) Adds multiple records to the store. Optionally, prevents re-rendering if freeze is true.
update(row, where, freeze?) Updates records based on the condition specified in where.
updateAll(row, freeze?) Updates all records in the store. Optionally, prevents re-rendering if freeze is true.
delete(where, freeze?) Deletes records based on the condition specified in where.
move(oldIdx, newIdx, freeze?) Moves a record from one index to another.
clearAll(freeze?) Clears all records from the store. Optionally, prevents re-rendering if freeze is true.
getAll(args?) Retrieves all rows from the store.
find(where, args?) Finds rows based on a condition specified in where.
findFirst(where, freeze?) Finds the first row that matches the condition in where.
findById(_id, freeze?) Finds a row by its _id.
setMeta(key, value, freeze?) Sets a value for a specific meta key.
getMeta(key, freeze?) Retrieves the value of a specific meta key.
getAllMeta(freeze?) Retrieves all meta data from the store.
deleteMeta(key, freeze?) Deletes a specific meta key.
clearMeta(freeze?) Clears all meta data from the store.

Example of the find Method

The find method allows you to search for rows in the store based on specific conditions:

npm install react-rock
Copy after login
Copy after login
Copy after login

Re-rendering in React Components

React-Rock optimizes re-renders by offering a freeze mechanism. When a store update occurs and the freeze option is enabled, React components that access the store using methods like find or findFirst will not automatically re-render. This gives you control over when your components should re-render, improving performance in large applications.

WhereType

The WhereType is used to specify conditions when querying rows. It defines a query structure for filtering rows.

QueryValueType

The QueryValueType is used within WhereType to define possible conditions for querying:

Property Description
contain Finds values containing the specified string, number, or boolean.
startWith Finds values that start with the specified string or number.
endWith Finds values that end with the specified string or number.
equalWith Finds values that are exactly equal to the specified value.
notEqualWith Finds values that are not equal to the specified value.
gt Finds values greater than the specified number.
lt Finds values less than the specified number.
gte Finds values greater than or equal to the specified number.
lte Finds values less than or equal to the specified number.

Example of WhereType

import { createStore } from 'react-rock';

// Define RowType and MetaType
type RowType = { name: string, age: number };
type MetaType = { totalRecords: number };

// Create a store
const users = createStore<RowType, MetaType>({ name: '', age: 0 }, { totalRecords: 0 });

// Add a new row to the store
users.create({ name: 'John Doe', age: 30 });
Copy after login
Copy after login
Copy after login

ArgsType

The ArgsType defines options for customizing query behavior, such as selecting specific rows or skipping rows.

Property Description
getRow Custom function to process rows before returning them.
skip Number of rows to skip.
take Number of rows to return.
freeze If true, prevents re-rendering when accessing the data.

Example with Class Component

To use the store in a class component, extend the StoreComponent class:

npm install react-rock
Copy after login
Copy after login
Copy after login

CRUD Example

import { createStore } from 'react-rock';

// Define RowType and MetaType
type RowType = { name: string, age: number };
type MetaType = { totalRecords: number };

// Create a store
const users = createStore<RowType, MetaType>({ name: '', age: 0 }, { totalRecords: 0 });

// Add a new row to the store
users.create({ name: 'John Doe', age: 30 });
Copy after login
Copy after login
Copy after login

Examples with find and Query

type RowType<Row> = Row & {
    _id: string;       // Unique identifier for the row
    _index: number;    // Index of the row in the store
    _observe: number;  // Internal property to track changes
}
Copy after login
Copy after login

Example of Using the Store in Multiple Components

React-Rock allows you to share the same store across multiple components, ensuring a consistent state throughout the app:

const foundUsers = users.find({ name: { equalWith: 'John Doe' } });
console.log(foundUsers);
Copy after login

Explanation of Types

  • RowType: Represents a record with an _id, _index, and _observe along with user-defined data fields.
  • ArgsType: Defines the options for querying rows with flexibility like skipping, taking, and custom row processing.
  • WhereType: Represents the conditions for querying records, using fields like contain, equalWith, and range queries like gt, lt, etc.
  • QueryValueType: Specifies the allowed condition types for filtering rows based on field values.

License

This package is licensed under the MIT License.


This documentation should provide a concise overview of how to use the react-rock package effectively.

? Contributing

Contributions are welcome! Please check out the contribution guidelines.


? License

This project is licensed under the MIT License.

The above is the detailed content of React Rock. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles