I'm trying to set a useState variable using an interface inside a createContext
. The goal is fetch some data inside someArray
and added into a useState. The following code uses react with typescript:
import { createContext, useState } from 'react';
export interface exportedInterface {
stateData: NftsData[];
fetchUnstakedNFTs: () => void;
}
interface Data {
dataString: string,
dataNumber: number,
}
export const customContext = createContext<exportedInterface>();
const CustomContext: FC = ({ children = null as any }) => {
const [stateData, setStateData] = useState<Data[]>([]);
let listDataArray: Data[] = [];
export const fetchSomeArray = async () => {
for (let item of someArray) {
await fetch(item.url)
.then(resp =>
resp.json()
).then((json) => {
const listData: Data = {
{
dataString: json.stringData,
dataNumber: json.numberData
}
listDataArray.push(listData)
}
}
setStateData(listDataArray) // this part doesn't work
}
console.log('stateData: ', stateData)
return (
<CustomContext.Provider
value={{
stateData,
fetchUnstakedNFTs,
}}
>
{children}
</CustomContext.Provider>
);
}
Then I create the context with the folowing file:
import { useContext } from 'react';
import { CustomContext } from 'aboveFile';
export const useCustomContext = () => {
const context = useContext(CustomContext);
if (context === undefined) {
throw new Error(
'CustomContext undefined'
);
}
return context;
};
Finally in other component I import the CustomContext
and run fetchSomeArray()
using useEffect
as in the following code:
import { useCustomContext } from 'aboveFile';
export default function App() {
const { fetchSomeArray } = useCustomContext();
useEffect(() => { fetchSomeArray() }, [])
return (
...
)
}
then I obtain the following output:
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 []