REACT_FULLSTACK [5] Client,Server - individual page based on id (table PK)

김병훈·2021년 9월 15일
0

REACT-FULLSTACK

목록 보기
5/10

add bar in App.js(Client)

<div className="navbar">
          <Link to="/createpost">새 글 작성</Link>
          <Link to="/"></Link>
        </div>

add codes for .navbar in App.css(Client)

/* NAVBAR */

.navbar {
  width: 100%;
  height: 70px;
  background-color: dodgerblue;
  display: flex;
  align-items: center;
  font-family: Arial, Helvetica, sans-serif;
}

.navbar a {
  margin-left: 20px;
  text-decoration: none;
  color: white;
}

add Another Route for post when I clicked just one of Posts

  • add Post.js in pages folder (Client)
  • rfce

in App.js (Client)

  • add some codes
import Post from './pages/Post';

<div className="navbar">
          <Link to="/"></Link>
          <Link to="/createpost">새 글 작성</Link>
        </div>

<Route path="/post/:id" exact component={Post} />

in page

Home.js (Client)

useHistory hook

and add onClick event in .post

  • import { useHistory } from 'react-router-dom';
  • let history = useHistory()

when I clicked first post (which id is 1)


  • it is rendering 1 because i put {id} in Post.js

Post.js 1

useParams hook

  • import { useParams } from 'react-router-dom';

Post.js 2fetch the data based on id

for to do that, use useEffect & axios

  • import React, { useEffect } from "react";

  • import axios from 'axios';

  • and use useEffect

in Posts.js in server folder (./route/Post.js)

  • add some codes
router.get('/byId/:id', async (req, res) => {
  const id = req.params.id;
  const post = await Posts.findByPk(id);
  res.json(post);
});

check api request in Postman

response in individual id page

  • code in Post.js (./pages/Post)(Client)
  • console

Creating a state which will allow us to hold that data

  • add useState
  • const [postObject, setPostObject] = useState({});
    • make a state
  • setPostObject(response.data)
    • and grab a data in response
  • return <div>{postObject.postText}</div>
    • we can see id:1's postText
    • postText rendering from page is real data from DB

    code in Post.js

  • left side will be individual post

  • right side will be comment place

    in page

  • id 1

  • id 3

    make a visual confirmation when we click Create Post button (작성완료 버튼)

  • for now, when I clicked Create Post , I was still in the page

  • so let's make that work how do we redirect based on if we clicked on the create post button

    in CreatePost.js (Client)

  • import { useHistory } from 'react-router-dom';

    • add useHistory
  • let history = useHistory();

    • put it at the top
  • history.push('/');

    • put it instead of console.log('IT WORKED') in onSubmit()

    check in Page

  • when I create a new post, it should redirect us to the 홈 which is just the slash.

  • when i clicked button?

  • redirect us to the 홈 page

profile
블록체인 개발자의 꿈을 위하여

2개의 댓글