D
D
danila_prokopenko2021-04-24 19:52:25
React
danila_prokopenko, 2021-04-24 19:52:25

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>
  );
};

vnGN643KWJA.jpg?size=1857x979&quality=96&sign=6c12f5431967530de10834fbc87efdb9&type=album
rm9GVMzn0pk.jpg?size=1850x792&quality=96&sign=6568076f09fc23b2747c4bbc19f198fa&type=album

working connection code
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()
  })


ooKhRqqgSIY.jpg?size=1852x110&quality=96&sign=f6b31a50e1778a9e5a23f3282e658d30&type=album

this is what I display on the main page
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>
  );
};

ZkXxBdtOWx8.jpg?size=1858x1006&quality=96&sign=0caeb42b2a2934586f5508fa0cb865b2&type=album

Dati-RH4sOI.jpg?size=1851x1002&quality=96&sign=1a8594af3c2e4730e78ae4cf3dc59a87&type=album

And on the main page, everything is displayed well from the state, but for some reason the data is not displayed on the page of an individual user, although the information itself is available.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan V, 2021-04-24
@verkhoturov

You are displaying data incorrectly.
The {user.movieName} entry would work if user were an object:

user = { 
   movieName: "", 
   movieReview: ""
}

But judging by the console, the "user" state is an array of one object.
user = [{ 
   movieName: "", 
   movieReview: ""
}]

Therefore, you can display the data by accessing the array at the index {user[0].movieName} .
Note that in the working example, before {user.movieName} is displayed , the users array is mapped to {users.map((user, index) => (...)}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question