The Book I Read #6

Lee·2022년 9월 30일
0

Toyproject

목록 보기
6/7
post-thumbnail

수정하기를 할 때, 해당 id에 따른 데이터를 가져와 화면에 뿌려주기 위해 :id 값에 따른 데이터를 조회할 수 있게 백과 프론트에 설정해주려고 한다. 일단 백부터 쿼리문을 작성해보자

id 값에 따른 데이터 조회하기 GET

  • index.js ( /backend )
    //선택된 데이터 가져오기
    app.get("/books/:id", (req, res) => {
      const bookId = req.params.id;
      const q = "SELECT * FROM books WHERE id = ?";
    
      db.query(q, [bookId], (err, data) => {
        if (err) return res.json(err);
        return res.json(data);
      });
    });
  • Update.js ( /Client)
    useEffect(() => {
        const getSelectData = async () => {
          try {
            const res = await axios.get("http://localhost:8800/books/" + path);
            setBook(res.data[0]);
          } catch (err) {
            console.log(err);
          }
        };
        getSelectData();
      }, [path]);
    Warning: A component is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
    Client 쪽에 input value값 설정 시 위와 같은 오류가 나왔는데 undefined일 경우의 값을 설정해줌으로 해결했다.
    <input
              type="number"
              placeholder="price"
              value={book.price || ""}
              onChange={handleChange}
              name="price"
            />

위와 같이 정상적으로 데이터를 가져오는 것을 확인할 수 있다. 이상 id값에 따른 데이터 값을 가져오기 성공 다음은 리펙토링을 해볼 예정이다.

profile
Lee

0개의 댓글