Home > Software design >  getting undefined in thunk response
getting undefined in thunk response

Time:01-03

I am using react with redux tookit to call my api and store my response in the state, but whenever i am calling the async thunk i am getting undefined in response but i am log my response in api, i am getting the expected response, i didn't know as i am beginner in redux, can anybody please help me what i am doing wrong. below is my memory slice reducer

import { RecentPublishedApi } from "../../components/api/api";

export const fetchMemoryAsync = createAsyncThunk(
  "memory/recentPublishedApi",
  async (obj) => {
    const response =await RecentPublishedApi(obj);
    console.log("i am inside the thunk",response)
    return response;
  }
);
const initialState = {
  data: [],
  status: "",
};

export const MemorySlice = createSlice({
  name: "memory",
  initialState,
  reducers: {
  },
  extraReducers: {
    [fetchMemoryAsync.pending]: (state) => {
      state.status = "loading";
    },
    [fetchMemoryAsync.fulfilled]: (state, action) => {
      console.log("fulfilled")
      state.status = "idle";
      console.log(action)
      state.data=action.payload;
    },
    [fetchMemoryAsync.rejected]: (state, action) => {
      state.status = "failed";
      state.error = action.payload;
    },
  },
});

export const selectData = (state) => state.memory.data;

export default MemorySlice.reducer;

my code sandbox link- https://codesandbox.io/s/hidden-snowflake-px34f?file=/src/App.js

CodePudding user response:

Your redux-thunk looks fine, it is your api function.

axios.post already returns a promise, so wrapping it all in a promise just returns a promise inside a promise.

import axios from "axios";

export const RecentPublishedApi = async (data) => {
  const headers = {
    "Content-Type": "application/json",
    "X-CSRF-TOKEN": "e7lwcn_OBGJuu2QsIA8auXzsvi9RGlzueRGDDwVsSKU"
  };

  return axios
    .post("https://public.cuebackqa.com/api/timeline/list", data, {
      headers: headers
    })
    .then((res) => {
      return res.data;
    })
    .catch((err) => {
      //throw an application exception
    });
};

  • Related