My goal is to develop a dynamic array that can store data fetched from a database through an HTTP request using a SQL query. Since I lack direct access to the database, my only option is to submit a query to retrieve the required information. The retrieved data will be stored in a reactive state that I have established. Here is a snippet of my code:
const dataState: any = reactive({
items: [],
});
function fetchData(query: string) {
query = `SELECT * FROM dept_sales WHERE store_id = 1 AND date = 20181114`;
axios
.post(`url_link`, query)
.then((response) => {
dataState.items = response.data;
})
}
To enhance my TypeScript skills, I am aiming to introduce typing to avoid using 'any'. Knowing the structure of the incoming data, I have defined an interface and a class as follows:
interface ISalesInfo {
storeId: number;
salesAmount: number;
salesQuantity: number;
salesDepartment: number;
}
class SalesData implements ISalesInfo {
storeId: number;
salesAmount?: number;
salesQuantity?: number;
salesDepartment?: number;
constructor(
storeId: number,
salesAmount: number,
salesQuantity: number,
salesDepartment: number
) {
this.storeId = storeId;
this.salesAmount = salesAmount;
this.salesQuantity = salesQuantity;
this.salesDepartment = salesDepartment;
}
}
My objective is to iterate through the data within dataState.items, create a new instance of SalesData for each iteration, and append it to a new typed array.
let salesList = reactive({}); // works, but remains typed as 'any'
let salesList: Array<SalesData> = []; // successfully compiles with proper typing,
//but lacks reactivity resulting in rendering issues on screen.
function typeSales() {
for (let i = 0; i < dataState.items.length; i++) {
salesList[i] = new SalesData(
dataState.items[i].ds_store_id,
dataState.items[i].ds_amt,
dataState.items[i].ds_qty,
dataState.items[i].ds_dept
);
Is there a method to establish a reactive array that is correctly typed (containing objects of type SalesData)?