Answer the question
In order to leave comments, you need to log in
Why can't I get data from State?
I have a state, values that I took from the database. The data that I took is available, it can be seen from the console and the state itself, but for some reason I cannot display it on the page.
const User = () => {
// const [user, setUser] = useState({
// movieName: "",
// movieReview: ""
// });
const [user, setUser] = useState([]);
const { id } = useParams();
useEffect(() => {
loadUser();
}, []);
const loadUser = async () => {
const result = await axios.get(`http://localhost:3002/api/${id}`);
setUser(result.data);
console.log("Стейт юсера ", result.data)
};
return (
<div className="container py-4">
<Link className="btn btn-primary" to="/">
back to Home
</Link>
<h1 className="display-4">User Id: {id}</h1>
<hr />
<ul className="list-group w-50">
<li className="list-group-item">movieName: {user.movieName}</li>
<li className="list-group-item">movieReview: {user.movieReview}</li>
</ul>
</div>
);
};
app.get("/api/:id", (req, res) => {
console.log("Fetching user with id: " + req.params.id)
const userId = req.params.id
const queryString = "SELECT * FROM `movies_reviews` where id = ?"
db.query(queryString, [userId], (err, rows, fields) => {
if (err) {
console.log("Failed to query for users: " + err)
res.sendStatus(500)
return
}
console.log("I think we fetched users successfully")
console.log("ID is: ", req.params.id)
const users = rows.map((row) => {
return {id:row.id, movieName: row.movieName, movieReview: row.movieReview}
})
res.json(users)
})
//res.end()
})
const Home = () => {
const [users, setUser] = useState([]);
useEffect(() => {
loadUsers();
}, []);
const loadUsers = async () => {
const result = await axios.get("http://localhost:3002/api/get");
setUser(result.data);
console.log("Стейт пользователей", result.data)
};
return (
<div className="container">
<div className="py-4">
<h1>Home Page</h1>
<table class="table border shadow">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">id</th>
<th scope="col">Name</th>
<th scope="col">User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr>
<th scope="row">{index + 1}</th>
<td>{user.id}</td>
<td>{user.movieName}</td>
<td>{user.movieReview}</td>
<td>
<Link class="btn btn-primary mr-2" to={`/users/${user.id}`}>
View
</Link>
<Link
class="btn btn-outline-primary mr-2"
to={`/users/edit/${user.id}`}
>
Edit
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
Answer the question
In order to leave comments, you need to log in
You are displaying data incorrectly.
The {user.movieName} entry would work if user were an object:
user = {
movieName: "",
movieReview: ""
}
user = [{
movieName: "",
movieReview: ""
}]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question