rempei
@rempei

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Redux action.payloadがうまく動かない

Q&A

Closed

解決したいこと

 loginUserというstateを更新するアクションsetUserを作成しました。
 ログインフォームに入力したものをsubmitするとその値にstateを更新するようにしていますが、更新されなくて困っています。
 どなたかお助けください

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

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    loggedIn: false,
    loginUser: "",
  },
  reducers: {
// 別のアクションを省略

    setUser: (state, action) => {
      state.loginUser = action.payload
    }
  },
});

export const { login, logout, setUser } = authSlice.actions;

export default authSlice.reducer;
function LoginForm() {

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const loggedIn = useSelector((state) => state.auth.loggedIn)
  const loginUser = useSelector((state) => state.auth.loginUser)
  const dispatch = useDispatch()
  const navigate = useNavigate()

  useEffect(() => {
    loggedIn && navigate("/main")
  }, [ loggedIn ])

  const handleSubmit = (e) => {
    e.preventDefault();
    if (username && password) {
      dispatch(login())
      dispatch(setUser(username))
      console.log('ログイン成功');
      console.log('state loginUser:' + loginUser);
      console.log('user:' + username);
    } else {
      console.log('ユーザー名とパスワードを入力してください');
    }
  };

return (

// 省略
        <form>
            // 省略
            <input
              type="text"
              id="username"
              name="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          <button type="submit" className="submit-btn">ログイン</button>
        </form>
  );
"@reduxjs/toolkit": "^1.9.6",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.1.2",
    "react-router-dom": "^6.16.0",
    "react-scripts": "5.0.1",
    "redux": "^4.2.1",
    "web-vitals": "^2.1.4"
0

No Answers yet.

Your answer might help someone💌