I'm trying to set a useState variable using an interface. The goal is parse the data inside someArray
and added into a useState. The following code uses react with typescript:
import { useState } from 'react';
interface Data {
dataString: string,
dataNumber: number,
}
export default function App() {
const [stateData, setStateData] = useState<Data[]>([]);
export const fetchSomeArray = async () => {
for (let item of someArray) {
setStateData((prev) => [
...prev,
{
dataString: item.stringData,
dataNumber: item.numberData
}
]); // this part doesn't work
}
}
console.log('stateData: ', stateData)
return (
<div className="App">
<h1>Title Text</h1>
</div>
);
}
In other file of my code I run await fetchUnstakedNFTs()
obtaining the following outputs:
stateData: [] // HERE IS THE ISSUE
I don't know why useState setStateData
is not working since stateData
value is []
I tried to use await new Promise((resolve) => setTimeout(resolve, 1500));
before console.log('stateData: ', stateData)
to give it time to update the state of stateData
and still getting []
CodePudding user response:
The following be a working version of what you were trying to do
import "./styles.css";
import { useState } from "react";
interface Data {
dataString: string;
dataNumber: number;
}
export default function App() {
const [stateData, setStateData] = useState<Data[]>([]);
const addToData = () => {
setStateData((prev) => [
...prev,
{
dataString: "data",
dataNumber: 2
}
]);
};
console.log("stateData: ", stateData);
return (
<div className="App">
<h1>Title Text</h1>
<h2>Subtitle text</h2>
<button onClick={addToData}>Press ME</button>
</div>
);
}
CodePudding user response:
You haven't called FetchSomeDataArray() function anywhere that's why your state is still an empty array. If you want it to be called before rendering it then wrap this in the UseEffect hook with an empty dependency list.
or You can trigger this function on any event like button clicking, hovering etc.
Here is code for how you can use useEffect hook:
useEffect( async () => {
// fetch some data function declaration
const fetchSomeDataArray = async () => { .... };
// function call
await fetchSomeDataArray();
},[])
CodePudding user response:
If you want to directly update your state, you can use useEffect
like this :
useEffect(() => {
fetchSomeArray()
}, []);
And you can remove the export of the function fetchSomeArray