VsCode로 출력창을 관리할 때 다음과 같은 시각적 어려움이 도사릴 수 있다.

 

우선 아래와 같은 내용으로 노트북을 작성한 후

from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI(
    temperature=0.1,    
)

chat.predict("How do you make 김치전")
​

 

출력을 진행하면,

스크롤이 좌우로 끊임없이 이어진다.

이런 경우 해결 방법은, Setting을 건드리는 법이다.

구체적은 해결 방안은 다음과 같다.

 


 

해결방안!!!

 

1. VsCode 설정 열기: Vscode에서 File > Preferences > Settings을 연다

2. wrap 검색: 이때 'wrap'이라 검색해서 관련 설정을 찾는다.

3. Notebook>Output.Word Warp을 클릭 한다.

 

이제 다시 한 번 출력해보자.

 

자동으로 줄이 바뀐걸 확인할 수 있다.

 

Next.js의 Redux를 이용해 " 투두리스트"를 만들어보자.

 

### useState

### Redux, selector, dispatch, slice

### Next.js 14

 


1. 폴더 구조

현재 Next.js 14버전을 이용했으며, AppRouter기반으로 진행하였다.

watch.tsx는 프로젝트에 필요한 파일은 아니다.
완성화면은 다음과 같다


2. 전체코드

 

[Page.tsx]

'use client';
import { useState } from 'react';
import { add } from '../slice/todolistSlice';
import { useAppSelector, useAppDispatch } from '../redux/hook';

export default function Home() {
  const [text, setText] = useState<string>('');

  const toDoList = useAppSelector((state) => state.todo.toDos); // slice의 이름
  const dispatch = useAppDispatch();

  const onChange = (e: any) => {
    setText(e.target.value);
  };
  const onSubmit = (e: any) => {
    e.preventDefault();
    dispatch(add(text)); // 자료 추가
    console.log(toDoList);
    setText('');
  };
  return (
    <div>
      <h1>To Do List</h1>
      <form onSubmit={onSubmit}>
        <input type='text' value={text} onChange={onChange} />
        <button>Add</button>
      </form>
      <ul>
        {toDoList.map((toDo) => (
          <li key={toDo.id}>{toDo.text}</li>
        ))}
      </ul>
    </div>
  );
}

 

[todolistSlice.ts]

import { createSlice } from '@reduxjs/toolkit';

type InitialState = {
  toDos: {
    text: string;
    id: number;
  }[];
};

const initialState: InitialState = {
  toDos: [],
};

export const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    add: (state, action) => {
      state.toDos.push({
        text: action.payload,
        id: Date.now(),
      });
    },
  },
});

export const { add } = todoSlice.actions;

export default todoSlice.reducer;

 

[store.ts]

import { configureStore } from '@reduxjs/toolkit';

import todoSlice from '@/slice/todolistSlice';

export const store = configureStore({
  reducer: { todo: todoSlice },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

 

[provider.tsx]

'use client';
import { store } from './store';
import { Provider } from 'react-redux';

type Props = {
  children: React.ReactNode;
};

export default function ReduxProvider({ children }: Props) {
  return <Provider store={store}>{children}</Provider>;
}

 

[hook.ts]

import { useDispatch, useSelector } from 'react-redux';
import type { TypedUseSelectorHook } from 'react-redux';
import type { RootState, AppDispatch } from './store';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

 

[layourt.tsx]

import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import ReduxProvider from '../redux/provider';

const inter = Inter({ subsets: ['latin'] });

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang='en'>
      <body>
        <ReduxProvider>{children}</ReduxProvider>
      </body>
    </html>
  );
}

 


 

redux에 대해서 더 공부하고 싶다면, 공식 홈페이지를 확인해 보자.

https://redux.js.org/introduction/getting-started

 

Getting Started with Redux | Redux

Introduction > Getting Started: Resources to get started learning and using Redux

redux.js.org

 

다음 시간에는, 리스트 제거를 진행해보자.

 

Next.js의 Hook을 이용해 시계를 만들어 보자.

 

### useState

### useEffect

### new Date()


1. 전체 코드

오늘 사용한 전체 코드는 다음과 같다.

'use client';
import { useState, useEffect } from 'react';

export default function Home() {
  const [currentTime, setCurrentTime] = useState(
    new Date().toLocaleTimeString()
  );

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h1>현재 시간</h1>
      <p>{currentTime}</p>
    </div>
  );
}

 

실제 화면


2. 코드 설명

const [currentTime, setCurrentTime] = useState(
    new Date().toLocaleTimeString()
  );

- useState를 사용하여 현재시간을 관리하는 상태 변수를 생성함.

- 초기값은 "new Date().toLocaleTimeString()"으로 현재 시간으로 설정함.

 

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

- useEffect 훅을 사용하여 마운트 될 때 동작 수행을 지정

- setInterval을 사용하여 1초(1000)마다 현재 시간 업데이트

- setCurrentTime()을 통해 갱신된 시간 저장

- return () => clearInterval(interval): 메모리 누수를 방지하기 위해, setInterval을 정리

 

return (
    <div>
      <h1>현재 시간</h1>
      <p>{currentTime}</p>
    </div>
  );
}

 

- JSX문법을 통해 실제 화면 렌더링

- {currentTime}에서 1초마다 새로운 시간 갱신

+ Recent posts