Home > Software design >  When i am trying to call the api using thunk , i am getting undefined
When i am trying to call the api using thunk , i am getting undefined

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 { addData } = MemorySlice.actions;
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:

You are not returning anything from your RecentPublishedApi. Add a return statement.

Also, that Promise you build there is already a promise, no need to wrap that manually.

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
      })
};
  • Related