I'm trying to update the state of my component with useState, using data received with axios. The problem is that "setCursos" doesn't update "cursos", which starts as an empty array. I have tried a lot of things but none of them seems to work. Please help. This is what a have so far:
import React, {useState, useEffect} from 'react';
import axios from 'axios';
const CursosAdmin = (props) => {
const [cursos, setCursos] = useState([]);
useEffect(() => {
axios
.get('/api/cursos')
.then(res => {
setCursos(cursos => [...cursos, res.data]);
console.log(cursos);
})
}, []);
return(
<div>
<h1>pagina de admin</h1>
</div>
);
}
export default CursosAdmin;
and this is what I have in express:
const router = require('express').Router();
const cursosData = require('../jsonFiles/cursosData.json');
let listaCursos = cursosData.cursos;
router.get('/', (req, res) => {
console.log(listaCursos);
res.send(listaCursos);
res.status(200);
});
module.exports = router;
aaand the json file where I'm getting the data:
{
"cursos": [
{
"id_curso": 0,
"curso_nombre": "IPC2",
"secciones": [],
"universidad": "Universidad de San Carlos de Guatemala"
}
]
}