Reputation: 11
The data does not appear in the table in the view. Importing data from db was confirmed with the console.enter image description here
If it is simply used as list.map(), an error saying that it is not a function occurs. So list && list.length > 0 ? I am using list.map((e). Or do I have to modify the const [list, setList] = useState code part?
import React, { useEffect, useState } from "react";
import axios from 'axios';
import Navbar from './Navbar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
export default function Community() {
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
useEffect(() => {
axios.get('http://localhost:5000/post/community').then((res) => {
console.log("성공");
console.log(res.data);
setList(res.data);
})
}, [])
return (
<div>
<Navbar />
<Box>
<Button sx={{ fontWeight: 'bold' }} href="/newpost">게시글 등록</Button>
</Box>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 'bold' }}>Post_id</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Title</TableCell>
<TableCell sx={{ fontWeight: 'bold' }} align="right">Writer</TableCell>
</TableRow>
</TableHead>
{list && list.length > 0 ? list.map((e) => {
return (
<TableBody>
<TableRow key={e.post_id}>
<TableCell component="th" scope="row">{e.post_id}</TableCell>
<TableCell align="right">{e.title}</TableCell>
<TableCell align="right">{e.writer}</TableCell>
</TableRow>
</TableBody>
)
}) : ""}
</Table>
</TableContainer>
</div>
);
}
Upvotes: 1
Views: 1665
Reputation: 921
Your first state is set up wrong which is then causing the map not to update the state data. It will only mutate not update.
Change
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
To this
const [list, setList] = useState([])
Upvotes: 1