Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

ksw_devlog

TIL 01.27 본문

TIL

TIL 01.27

kimcoach 2023. 1. 29. 02:34

useQuery로 받아온 데이터를 navigate를 통해 props를 전달해주는 코드를 짰다. 추후에 다시 정리해서 설명예정...

import axios from "axios";

const BASE_URL = 'http://localhost:3001';

export const videoApi = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-type': 'application/json',
  }
});

// export const createVideo = async () => {
//   // const response = await videoApi.post('/videos');
//   const response = await axios.post('http://localhost:3001/videos');
//   return response.data;
// }

// export const createVideo = (id) => axios.post('http://localhost:3001/videos', id)

export const createVideo = (id) => videoApi.post('/videos', id);

export const editVideo = ({id, title, content}) => videoApi.patch(`/videos/${id}`, {
  title,
  content,
});

export const deleteVideo = (id) => videoApi.delete(`/videos/${id}`);

a

import axios from "axios"
import { useQuery } from "react-query"
import { useNavigate } from "react-router-dom";


export default function TestHome() {
    const navigate = useNavigate();
    //result 데이터 : 배열
    const result = useQuery("videos", () =>
        axios.get('http://localhost:3001/videos')
        .then((a) => a.data)
    );
    //http://localhost:3001/videos/${id} -> 객체
    // const resultId = useQuery("videos", (id)=>
    //     axios.get(`http://localhost:3001/videos/${id}`)
    //     .then((b) => b.data)
    // )
    // console.log('resultId', resultId)
    // console.log('video', result.data[0])
    
    

    const goToDetail = (i) => {
        navigate(`/testDetailPage/${result.data[i]?.id}`, {
            state: {
                videodata: result.data[i]
            }
        });
    };

    return (
        // result데이터로 map함수 이용 -> 배열안에 객체별로 navigate state넘겨주기
        <div>
            {result.isLoading && 'Loading...'}
            {result.error && 'error'}
            {result.data?.map((a, i)=>(
                <div key={a.id} style={{backgroundColor: 'skyblue'}}>
                    <p>{result.data[i].title}</p>
                    {result.data[i].content}
                    <button onClick={()=>goToDetail(i)}>상세페이지로</button>
                </div>
            ))}
        </div>
    )
}

b

import axios from "axios";
import { useQuery } from "react-query";
import { useLocation, useNavigate, useParams } from "react-router";

export default function TestDetailPage() {
    const { path } = useParams()
    const location = useLocation();
    const navigate = useNavigate();
    const { videodata } = location.state || {};
    console.log(path)
    console.log('state', videodata)
    console.log('videodata', videodata?.title)
    // const result = useQuery("videos", ()=>
    //     axios.get(`http://localhost:3001/videos/a9edb26d-ad64-40a7-bf16-d3e2bebfbc59`)
    //     .then((a)=>{return a.data})
    // );
    
    const goToeditPost = () => {
        navigate('/editpost', {
            state: {
                videoId: videodata.id,
                videotitle: videodata.title,
                videocontent: videodata.content
            }
        });
    };

    return (
        <div style={{backgroundColor: 'yellow'}}>
        <p>
        제목 : {videodata?.title}
        </p>
        내용 : {videodata?.content}
        <button onClick={goToeditPost}>수정페이지로</button>
        </div>
    );
};

c

import { useState } from 'react';
import { useMutation, useQueryClient } from 'react-query';
import { useLocation, useNavigate } from 'react-router';
import styled from 'styled-components';
import { editVideo } from '../API/postApi';

export default function EditPostPage() {
  const location = useLocation();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  // console.log('state', location.state)
  const { videoId, videotitle, videocontent } = location.state;
  // const videotitle = location.state.title;
  
  // const videocontent = location.state.content;
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');

  const reviseVideo = useMutation((video) => editVideo(video), {
    onSuccess: (data) => {
      console.log(data);
      queryClient.invalidateQueries(['videos']);
    },
    onError: (error) => {
      console.log(error);
    },
  });

  const handleEdit = (e) => {
    e.preventDefault();
    const editObj = {
      id: videoId,
      title: newTitle,
      content: newContent,
    };
    reviseVideo.mutate(editObj);
    navigate(`/testHome`)
  };

  return (
    <Container>
      <Text>게시물 수정</Text>
        <Form>
        {/* {placeholder= 받아온 데이터} */}
        <Input 
          type={'text'} 
          maxLength={'120'}  
          placeholder={videotitle}
          onChange={(e) => setNewTitle(e.target.value)}
         />
        <Textarea 
          type={'text'} 
          placeholder={videocontent}
          onChange={(e) => setNewContent(e.target.value)}
          ></Textarea>
        <BtnBox>
        <Button onClick={handleEdit} style={{marginRight:'20px'}}>
          수정
        </Button>
        <Button type='button' onClick={()=>navigate(-1)}>취소</Button>
        </BtnBox>
        </Form>
    </Container>
  )
}
const Container = styled.div`
  margin-top: 50px;
  margin-left: 160px;
`
const Text = styled.p`
  font-size: 30px;
  font-weight: 600;
`
const Form = styled.form`
  display: flex;
  flex-direction: column;
`
const Input = styled.input`
  width: 1600px;
  height: 60px;
  margin-bottom: 30px;
  border-radius: 10px;
  border: 1px solid;
  font-size: 25px;
  padding: 10px;
  outline: none;
`
const Textarea = styled.textarea`
  width: 1600px;
  height: 500px;
  border-radius: 10px;
  border: 1px solid;
  margin-bottom: 35px;
  resize: none;
  font-size: 25px;
  padding: 10px;
  outline: none;
`
const BtnBox = styled.div`
  display: flex;
  justify-content: end;
  margin-right: 125px;
  margin-bottom: 10px;
`
const Button = styled.button`
  width: 100px;
  height: 40px;
  color: white;
  background-color: #C4302B;
  border-radius: 20px;
  border: none;
  cursor: pointer;
  font-size: 17px;
`

 

 

 

 

 

 

 

 

 

 

'TIL' 카테고리의 다른 글

TIL 01.30 React 프로젝트 회고  (0) 2023.01.30
WIL 13주차  (0) 2023.01.30
TIL 01.26  (0) 2023.01.26
TIL 01.25  (0) 2023.01.25
WIL 12주차  (0) 2023.01.24