0

I've a RTK query which takes email and password as arguments and returns login info from the server.

RTK QUERY code


const authService = createApi({
  reducerPath: "auth",
  baseQuery: fetchBaseQuery({ baseUrl: "http://localhost:8000/auth/" }),
  endpoints: (builder) => ({
    authLogin: builder.mutation({
      query: ({ email, password }) => ({
        url: "login",
        method: "POST",
        body: { email, password },
      }),
    }),
  }),
});

Function which invokes authLogin(from elsewhere) by passing email and password as required by the query.


const [authLogin, response] = useAuthLoginMutation();

  const handleLogin = (e) => {
    e.preventDefault();
    authLogin({ email, password });
  };

I don't understand why despite being destructured as ({email, password}) in authLogin query call, the body still takes in email and password with curly braces? If email and password are already destructured in the query call, shouldn't the code be body:(email, password) instead of body:{email, password}?

I do realize that I'm missing something very basic(regarding objects and destructuring), perhaps someone could explain where I'm going wrong in simple words.

1 Answers1

0
body: { email, password },

is just the shorthand version of

body: { email: email, password: password },

No destructuring going on at this point, just a POJO.


Using

body: (email, password)

would also be valid syntax using the comma operator, but it would result in body being assigned the string password.

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.

connexo
  • 53,704
  • 14
  • 91
  • 128
  • Okay, I think I understand now. Also in query:({email, password}), the email and password are destructured right? So if it is, can I also write props( as in query:(props)) and later use it inside body? Like body:({email:props.email, password:props.password}). Are they the same? – Krishna Bharadwaj Sep 10 '22 at 12:42
  • Yes, they are the same in result, just not using destructuring, which allows for far more consise code. – connexo Sep 10 '22 at 13:38