0

userSlice

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import LoginService from "../../Services/Login.service";

export const userRegister = createAsyncThunk(
  "users/register",
  async (params) => {
    try {
      const { registerForm } = params;
      const { data } = await LoginService.register(registerForm);

      return data;
    } catch (error) {
    }
  }
);

const initialState = {
  userData: {},
  errorResponse: null,
  status: "idle",
};

export const userSlice = createSlice({
  name: "User",
  initialState,
  reducers: {},
  extraReducers: {
    [userRegister.pending]: (state, action) => {
      state.status = "loading";
    },
    [userRegister.fulfilled]: (state, action) => {
      state.status = "succeeded";
      state.userData = action.payload;
    },
    [userRegister.error]: (state, action) => {
      state.status = "failed";
      state.errorResponse = action.payload;
    },
  },
});

export default userSlice.reducer;

Login.service.js

import axios from "axios";

const API = axios.create({ baseURL: 'http://localhost:3001'});

const LoginService = {

    register: async (registerData ) => {
         await API.post('/users/register', registerData)
    } 
};

export default LoginService;

Hi.I try add register feature to my app. But when i submit register form, the datas is saved to the database without any problems. But this line const data = await LoginService.register(registerForm); doesnt work data is undefined but when i same post request in postman i get response data the way i want.

Umut Palabiyik
  • 313
  • 6
  • 16
  • Currently, you're destructuring the return value of `register`, pulling out `data`, which may be undefined. Have you tried logging the entire object returned by `await LoginService.register(registerForm)`? – DustInComp Nov 28 '21 at 18:27

1 Answers1

1

LoginService.register is not returning anything, you can fix that by doing:

const LoginService = {
    register: async (registerData ) => {
         const response = await API.post('/users/register', registerData);
         
         return response.data;
    } 
};
  • 1
    This is fine, but since OP is already destructuring the return value with `const { data } = ...` it can be simplified by removing the curly braces from the definition, and even `async` is unnecessary because they're already `await`ing the call. `register: registerData => API.post('/users/register', registerData);` – Matt U Nov 28 '21 at 18:57