I have an both an array, and the state array.
const [formData, setFormData] = useState([]);
let ure = [{}]
useEffect(() => {
axios
.get("/api/listUre")
.then((res) => {
console.log(res.data)
//setFormData(res.data);
ure.push({
class_id: res.data.class_id
})
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
.finally(() => {
});
}, []);
once I do that, I now want to access the class_id from within a table:
{ure.length > 0 &&
ure.map((obj, index) => {
<tr key={index}>
<td>
{obj.class_id}
</td>
<td>
{obj.class_id}
</td>
<td>
My Name
</td>
</tr>
})}
{ure.length === 0 && "No Data Found"}
I am not sure what I am doing wrong, but it is not outputting anything to the page. and i know that the ure array has data in it because it isn't outputting "No Data Found" to the screen, so it should be working. can anyone help me out?
I think you need ure to be a piece of state, otherwise your ure array will keep getting reevaluated each time your component re-renders.
So, the first step would be to:
const [ure, setUre] = useState([]);
Then for changing ure, just do something like:
setUre(currUre => {
return currUre.concat([{ foo: bar }]);
})
Then, to iterate over it, you shouldn't need to check the length > 0, just the map() will do the trick.
The reason why you're seeing that outcome (no table but no empty array) is because you're initializing let ure = [{}], which is an array of size 1 with an empty object in it.