I am having the following code:
const [FishClass, setFishClass] = useState({});
//...
useEffect(() => {
axios.get("/api/v1/class/" + params.id).then(
(response) => {
console.log("axios call: " + response.data);
if (Array.isArray(response.data)) {
setFishClass(response.data[0]);
} else {
setFishClass(response.data);
}
},
(error) => {
console.log(error);
}
);
}, []);
Two things are strange first setFishClass does not set the Object correctly. Second the Object sometimes seems to be an Array… What am i doing wrong and how can i solve this more elegant?
2
Answers
You have to understand better what
response.data
can look like.From what I understood
response.data
can be either an array or anobject
and based on that you set yourFishClass
state. cool and your code should work for that.however, you said that
FishClass
is sometimes an array. this can only happen whenresponse.data
is an array and andresponse.data[0]
is an array:[[{..}]]
so I think that you have to check with
response.data[0]
instead ofresponse.data
.my guess is that the endpoint is always returning an array, and it is either
[{..}]
of[[{..}]]
if you are not confirmed which data type the response data will be
you can simply modify your code. first set the data and then when you are using it for your specific use case then apply the conditions or destructure it.