Home > Article > Web Front-end > Use React Query and database for data backup and disaster recovery
Using React Query and database for data backup and disaster recovery requires specific code examples
In modern web development, data backup and disaster recovery are crucial a part of. Whether to protect user data from accidental deletion or system failure or to be able to quickly restore data to maintain business continuity, backing up and restoring data is essential.
React Query is an excellent data management library that provides powerful data query, caching and update capabilities. Combining React Query and the database, we can easily implement data backup and disaster recovery functions.
The following will introduce how to use React Query and database for data backup and disaster recovery, and give specific code examples.
1. Data backup
First, we need to configure a database to store backup data. Common choices include MySQL, MongoDB, etc. Here we take MySQL as an example to illustrate.
First, install MySQL and create a database and backup tables. You can use the following SQL statement:
CREATE DATABASE IF NOT EXISTS backupdb; USE backupdb; CREATE TABLE IF NOT EXISTS backup_table ( id INT PRIMARY KEY AUTO_INCREMENT, data TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Next, create a React Query query hook in the React application to retrieve data from the database Get backup data. You can use the following code:
import { useQuery } from 'react-query'; const fetchBackupData = async () => { const response = await fetch('/api/backupdata'); const data = await response.json(); return data; }; const useBackupData = () => { return useQuery('backupData', fetchBackupData); };
In the above code, we used the useQuery
hook to initiate an asynchronous request, and implemented the slave API interface in the fetchBackupData
function## The logic of obtaining backup data in #/api/backupdata.
useBackupData hook in the component to display backup data. The specific code is as follows:
import React from 'react'; import { useBackupData } from './hooks/useBackupData'; const BackupData = () => { const { isLoading, error, data } = useBackupData(); if (isLoading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error.message}</div>; } return ( <div> <h1>Backup Data</h1> <ul> {data.map((item) => ( <li key={item.id}>{item.data}</li> ))} </ul> </div> ); }; export default BackupData;In the above code, we use the
useBackupData hook in the component to obtain the backup data and display the corresponding UI according to the requested status. When the data is loading, "Loading..." is displayed. When an error occurs in the request, an error message is displayed. When the request is successful, the backup data is displayed.
const mysql = require('mysql'); const backupdb = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'backupdb', }); const createBackup = async () => { return new Promise((resolve, reject) => { backupdb.query('INSERT INTO backup_table (data) SELECT data FROM main_table', (error, results, fields) => { if (error) { reject(error); } else { resolve(results); } }); }); }; const backupOnChange = () => { const maindb = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'maindb', multipleStatements: true, }); maindb.query('SELECT @dummy := 0;'); maindb.on('change', () => { createBackup() .then(() => { console.log('Backup created successfully'); }) .catch((error) => { console.error('Failed to create backup:', error); }); }); }; backupOnChange();In the above code, we first create a MySQL connection to
backupdb, Then a
createBackup function is defined to insert data from
main_table into
backup_table. Then we created a MySQL connection to
maindb and used the
change event to monitor changes in data in the database. When the data changes, the
createBackup function is triggered. .
import { useMutation, useQueryClient } from 'react-query'; const notifyBackupService = async () => { const response = await fetch('/api/notifybackup', { method: 'POST' }); const data = await response.json(); return data; }; const BackupData = () => { const queryClient = useQueryClient(); const { mutate } = useMutation(notifyBackupService, { onSuccess: () => { queryClient.invalidateQueries('backupData'); console.log('Backup service notified'); }, onError: (error) => { console.error('Failed to notify backup service:', error); }, }); return ( <div> <h1>Backup Data</h1> <button onClick={() => mutate()}>Notify Backup Service</button> </div> ); };In the above code, we use the
useMutation hook to define a
notifyBackupService function, using Notify disaster recovery services. In the option parameters of the
useMutation hook, we use the
onSuccess callback function to refresh the backup data query and print a success notification message; we use the
onError callback function to Handles notification failures and prints an error message. At the same time, we added a button to the component. Clicking the button will trigger the
notifyBackupService function to notify the disaster recovery service.
The above is the detailed content of Use React Query and database for data backup and disaster recovery. For more information, please follow other related articles on the PHP Chinese website!