I'm really confused on how to do useState in React on an empty array
import "./styles.css";
import text from "./text.js";
import React, { useState } from "react";
export default function App() {
let allTheWords = text.split(" ");
let countData = [];
let theWordCount = {};
const createTable = () => {
for (const num of allTheWords) {
theWordCount[num] = theWordCount[num] ? theWordCount[num] + 1 : 1;
}
for (const property in theWordCount) {
countData.push(
<tr key={property}>
<td>{property}</td>
<td>{theWordCount[property]}</td>
</tr>
);
}
};
createTable();
const sortWords = () => {
theWordCount = Object.entries(theWordCount)
.sort(([, a], [, b]) => a - b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log("OKAY I THINK WE SORTED: " + JSON.stringify(theWordCount));
createTable();
};
return (
<div>
<button onClick={sortWords}>SORT WORDS</button>
<table>
<tbody>
<tr>
<th>Word</th>
<th>Count</th>
</tr>
{countData}
</tbody>
</table>
</div>
);
}
I need to somehow do useState on the variable countData so I can update the DOM when theWordCount changes.
https://reactjs.org/docs/hooks-state.html
I read through the above and got to this
import "./styles.css";
import text from "./text.js";
import React, { useState } from "react";
export default function App() {
let allTheWords = text.split(" ");
let countData = [];
let theWordCount = {};
countData = useState(0);
const createTable = () => {
for (const num of allTheWords) {
theWordCount[num] = theWordCount[num] ? theWordCount[num] + 1 : 1;
}
for (const property in theWordCount) {
countData.push(
<tr key={property}>
<td>{property}</td>
<td>{theWordCount[property]}</td>
</tr>
);
}
};
createTable();
const sortWords = () => {
theWordCount = Object.entries(theWordCount)
.sort(([, a], [, b]) => a - b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log("OKAY I THINK WE SORTED: " + JSON.stringify(theWordCount));
createTable();
};
return (
<div>
<button onClick={sortWords}>SORT WORDS</button>
<table>
<tbody>
<tr>
<th>Word</th>
<th>Count</th>
</tr>
{countData}
</tbody>
</table>
</div>
);
}
But the DOM doesn't update or do anything or give me any errors.
In this context how do you make countData converted into a state in the function?