NextJs - Board array 가져오기

choko's avatar
Jun 29, 2024
NextJs - Board array 가져오기
 
  1. axios config
    1. import axios from 'axios'; const instance = axios.create({ baseURL: 'http://localhost:8080/api', // api endpoint env.. timeout: 5000, // Set a timeout for requests (in milliseconds) headers: { 'Content-Type': 'application/json' }, }); export default instance;
 
  1. getBoards (axios)
    1. import axios from './axios' export const getBoards = (token:string) => { //noStore() try { return new Promise<any>((resolve, reject) => { const reqUrl = '/board'; axios.get(reqUrl, { headers: { // Bearer 토큰을 Authorization 헤더에 추가 'Authorization': `Bearer ${token}` } }) .then(res => { resolve(res.data.data); }, err => { reject(err.response.data.message); }) }) } catch (error) { console.error('Server Error:', error); throw new Error('Failed to connect server.'); } }
 
 
  1. getBoards()로 board list 가져오기
    1. useEffect(() => { const fetchBoards = async (token:string) => { try { const response = await getBoards(token); console.log(response) setBoards(response); } catch (error) { console.error('Error fetching boards:', error); } }; const accessToken = localStorage.getItem('accessToken'); if (isLoggedIn && accessToken) { fetchBoards(accessToken); } else { setBoards([]) } }, [isLoggedIn]);
      • useEffect의 2번째 인자로 isLoggedIn를 넣어, 로그인/로그아웃 시마다 데이터를 불러오도록 한다.
       
       
       
Share article

Tom의 TIL 정리방