Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

createAsyncThunk fulfilled not getting called after response received

In my fullfilled i am getting response as undefined. any one please help?

code :

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";


const fetchPost = createAsyncThunk('fetch/post', async (params: string) => {
    try {
            const { data } = await axios.get('https://registry.npmjs.org/-/v1/search', { params: { text: params } })
            data.objects.map((result: any) => {
                console.log('result', result)//getting result
                return result.package.name; 
            });
        } catch (err: any) {
            return err?.response;
        }
})

interface RepositoriesState {
    loading: boolean;
    error: string | null;
    data: string[];
}


const initialRepoState:RepositoriesState = {
    loading: false,
    error: null,
    data:[]
}


const repositorySlice = createSlice({
    name: 'repo-slice',
    initialState: initialRepoState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(fetchPost.pending, (state) => {
            state.loading = true
        })
        .addCase(fetchPost.fulfilled, (state, action) => {
            state.loading = false;
            state.data = action.payload;
            console.log('payload', action.payload) //undefined
        })
        .addCase(fetchPost.rejected, (state) => {
            state.loading = false;
            state.error = "error in api";
            state.data = [];
        })
    }
})
export { fetchPost };
export default repositorySlice.reducer;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Nothing is getting returned from your function… so its undefined

I guess it should be as so

const fetchPost = createAsyncThunk('fetch/post', async (params: string) => {
    try {
            const { data } = await axios.get('https://registry.npmjs.org/-/v1/search', { params: { text: params } })
            return data.objects.map((result: any) => {
                console.log('result', result)//getting result
                return result.package.name; 
            });
        } catch (err: any) {
            return err?.response;
        }
})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading