6. CRUD Operations
Perform Create, Read, Update and Delete calls.
Create, read, update, delete data records
Create data into the HAT
{
value: 'This is a note!',
dateCreated: "2020-05-20T10:17:10.398Z",
}// src/features/Notes/Notes.js
import React, { useContext, useState } from 'react';
import { HatClient } from '@dataswift/hat-js';
import './Notes.scss';
import { appConfig } from '../../app.config';
import AuthContext from "../../components/context/AuthContext";
function Notes() {
const [newNote, setNewNote] = useState('');
const authContext = useContext(AuthContext);
// The endpoint to store the Notes data
const notesEndpoint = 'my-notes';
// Create the configuration object to pass the auth token, api version and
// the ssl flag to the HAT-JS
const config = {
token: authContext.user.token,
apiVersion: appConfig.hatApiVersion,
secure: appConfig.secure,
};
// Initialize the HatClient with the configuration file
const hat = new HatClient(config);
const handleChange = event => {
setNewNote(event.target.value);
};
const handleSubmit = event => {
event.preventDefault();
createData();
};
const createData = async () => {
try {
if (!newNote) return;
const dateCreated = new Date().toISOString();
// Create the structure for the Note
const body = {
value: newNote,
dateCreated: dateCreated,
};
// Use the HAT-JS library to create our first data record
const res = await hat.hatData().create(appConfig.namespace, notesEndpoint, body);
if (res.parsedBody) {
// Reset the Note value
setNewNote('');
}
} catch (e) {
console.log(e.cause + e.state)
}
};
return (
<form
onSubmit={e => handleSubmit(e)}
>
<input
.
.
value={newNote}
onChange={e => handleChange(e)}
/>
.
.
</form>
);
}
export default Notes;Read data from the HAT
Update a data record
Delete data from the HAT
Last updated
Was this helpful?