I'm sorry in advance, this is for a professional project and I can't detail things, so I gotta explain things without telling the true terms.
I'm sending a GET request to an API. This API sends a response in this format :
[0:
[
0: { permission: 1
thing: { title: 'title' id: '1234'}
}
1: { permission: 1
thing: { title: 'title2' id: '5678'}
}
]
]
In my code, I have a state (use hooks) called things, and I wanna store the 'things' Axios send in response. More clearly, I wanna store the 0 and the 1 inside the big 0.
I made an interface like this one :
interface IThing {
id: string;
title: string;
permission: number;
};
in order to type my state like this :
const [things, setThings] = useState<IThing[]>();
Now, here's the function I use to get data from Axios and try to store it in my state (maybe it's important to precise that this function is in a useEffect) :
const getMyThings = async () => {
try {
const getThings = await axios.get(
"url",
{
headers: {
...
},
}
);
const result = getThings.data;
if (things) {
const newThings = [...things];
console.log(newProjects);
newThings.push(result);
setThings(newThings);
console.log(projects);
}
} catch (error) {
if (axios.isAxiosError(error)) {
console.log(error.response);
} else {
console.log(error);
}
}
In this function, the console.log(result) print the axios response. But once I push it in the state, a console.log() of things always returns undefined.
I also tried with this :
const newThings = [...(things || [])];
newThings.push(result);
console.log(newThings);
setThings(newThings);
console.log(things);
but the same thing happen : the console.log(newThings) returns the axios response, but the console.log(things) returns undefined.
One thing I saw is that my state is inferred by TypeScript as IThing | undefined, it probably comes from here but I don't know what to do as I'm new with TypeScript.
Thanks in advance for your help!