article 들(임시)

류한선·2024년 5월 13일

4차 프로젝트

목록 보기
31/53
'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import api from "@/util/api"
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'

export default function Article() {

    const getArticles = async () => {
        return await api.get('/articles')
            .then((response) => response.data.data.articles)
    }

    const {isLoading, error, data} = useQuery({
        queryKey: ['articles'],
        queryFn: getArticles
    });


    const deleteArticle = async (id) => {
        await api.delete(`/articles/${id}`)
    }

    const queryClient = useQueryClient()
    const mutation = useMutation({
        mutationFn: deleteArticle,
        onSuccess: () => {
            queryClient.invalidateQueries({queryKey: ['articles']})
        }
    })

    if (error) {
        console.log(error)
    }

    if (isLoading) <>Loading...</>

    if (data) {
        return (
            <>
                
                <ul>
                    번호 / 제목 / 작성자 / 생성일 / 삭제
                    {data.map((row) => (
                        <li key={row.id}>
                            {row.id} /{' '}
                            <Link href={`/article/${row.id}`}>{row.subject}</Link> /{' '}
                            {row.author} / {row.createdDate}
                            <button onClick={() => mutation.mutate(row.id)}>
                                삭제
                            </button>
                        </li>
                    ))}
                </ul>
                <Link href="/articleCreate">
    Article Create 페이지로 이동
</Link>

            </>
        )
    }


}
'use client'

import { useState } from 'react';
import api from '@/util/api';
import { useRouter } from 'next/navigation'; // 수정
import { useQueryClient } from '@tanstack/react-query';

export default function ArticleCreate() {
    const router = useRouter();
    const [article, setArticle] = useState({ subject: '', content: '' });

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await api.post('/articles', article);
            // 등록 성공 시, 이전 페이지로 이동하거나 사용자에게 알림을 제공할 수 있습니다.
            router.push('/article');
        } catch (error) {
            console.error('등록 중 에러:', error);
        }
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setArticle({ ...article, [name]: value });
    };

    return (
        <>
            <h3>글 등록</h3>
            <form onSubmit={handleSubmit}>
                <div>
                    <label>제목:</label>
                    <input type="text" name="subject" value={article.subject} onChange={handleChange} />
                </div>
                <div>
                    <label>내용:</label>
                    <textarea name="content" value={article.content} onChange={handleChange} />
                </div>
                <button type="submit">등록</button>
            </form>
        </>
    );
}

'use client'

import api from "@/util/api"
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation';

export default function ArticleEdit() {
    const params = useParams()
    const router = useRouter();

    const [isLoading, setIsLoading] = useState(false)
    const [article, setArticle] = useState({ subject: '', content: '' })

    useEffect(() => {
        fetchArticle()
    }, [])

    const fetchArticle = async () => {
        try {
            const response = await api.get(`/articles/${params.id}`)
            setArticle(response.data.data.article)
            setIsLoading(true)
        } catch (error) {
            console.log(error)
        }
    }

    const handleSubmit = async (e) => {
        e.preventDefault()
        try {
            await api.patch(`/articles/${params.id}`, article)
            router.push('/article');
        } catch (error) {
            console.log(error)
        }
    }

    const handleChange = (e) => {
        const { name, value } = e.target
        setArticle({ ...article, [name]: value })
    }

    return (
        <>
            {isLoading ? (
                <>
                    <h1>수정페이지</h1>
                    <form onSubmit={handleSubmit}>
                        <input
                            type="text"
                            name="subject"
                            value={article.subject}
                            onChange={handleChange}
                        />
                        <input
                            type="text"
                            name="content"
                            value={article.content}
                            onChange={handleChange}
                        />
                        <button type="submit">수정</button>
                    </form>
                </>
            ) : (
                <></>
            )}
        </>
    )
}

0개의 댓글