reactjsreact-reduxrtk-query

RTK query mutation returns status: uninitialized


I am trying to use redux-toolkit/query to make a POST request after which i want the get request to refetch all the users, but when I run the mutation query its result show that it was uninitialized even though I can see on the network tab that a POST request was made and after reloading the page it fetches the modified data (i am not creating or deleting data but actually modifying it, but the endpoint I was given is a POST instead of a PATCH idk if that could have an impact on whats happening).

this is the API slice

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import config from "../../config";

export const usersApi = createApi({
  reducerPath: "users",
  baseQuery: fetchBaseQuery({
    baseUrl: `${config.apiUrl}/api/security`,
  }),
  endpoints: (builder) => {
    return {
      fetchAllUsers: builder.query({
        providesTags: (result, error, arg) => {
          // console.log(result);
          const tags = result.data.map((user) => {
            return { type: "user", id: user.COD_USUARIO };
          });
          return tags;
        },
        query: (token) => {
          return {
            url: `UsuariosAll/${token}`,
            method: "GET",
            headers: { "content-type": "application/x-www-form-urlencoded" },
          };
        },
      }),
      setUser: builder.mutation({
        invalidatesTags: (result, error, user) => {
          return [{ type: "user", id: user.COD_USUARIO }];
        },
        query: ({ token, row }) => {
          console.log(row);
          return {
            url: `MenuByUsuario/${token}`,
            method: "POST",
            headers: { "content-type": "application/x-www-form-urlencoded" },
            params: {
              cod_usuario: row.COD_USUARIO,
              status_usuario: row.ESTADO === "ACTIVO" ? 0 : 1,
            },
          };
        },
      }),
    };
  },
});

export const { useFetchAllUsersQuery, useSetUserMutation } = usersApi;

this is the code where I want to run the mutation

import React, { useState, useEffect } from "react";
import { useSetUserMutation } from "../../../store/store";
import { useSelector } from "react-redux";

function Row({ row, columnaEstado, columnaVer, handleSelect, selected }) {
  const { session_id: token } = useSelector(({ session }) => session);
  // const [rowState, setRowState] = useState(row.ESTADO);
  const [setUser, result] = useSetUserMutation();

  if (row.RNUM == 2) console.log(row.ESTADO);
  const handleDoubleClick = (e) => {
    if (e.detail === 2) {
      setUser({ token, row });
      console.log(result);
    }
  };
  const { formatter: estadoFormatter } =
    columnaEstado;
  const { formatter: accionFormatter } = columnaVer;
  const selectedStyle = (selected) => {
    if (selected) {
      return { backgroundColor: "#eeeeee" };
    } else {
      return {};
    }
  };
  return (
    <tr
      key={row.COD_USUARIO}
      onClick={() => handleSelect(row)}
      style={selectedStyle(selected)}
    >
      <td>{row.RNUM}</td>
      <td>{row.ID_USUARIO}</td>
      <td onClick={handleDoubleClick}>{estadoFormatter(row.ESTADO)}</td>
      <td>{accionFormatter([], row)}</td>
    </tr>
  );
}

export default Row;

Solution

  • you cannot immediately access the result inside your function like that you have to use something like this if you need the response data in the same function

    setUser({ token, row })
    .unwrap()
    .then(fulfilled => {
    console.log(fulfilled)
    })
    .catch(rejected => console.error(rejected))
    

    here the response data is in 'fulfilled'. also if you just simply moved

    console.log(result);
    

    this outside of your function you would see it getting fulfilled

    see docs for more: https://redux-toolkit.js.org/rtk-query/usage/mutations