'react reducer toolkit dispatch not working

I wrote profile page I want to get profile datas from api but my dispatch not working, in getProfileDetails function dispatch not working.

import {createSlice} from "@reduxjs/toolkit";
import axios from "../components/axios";
import urls from "../components/Urls";
import authHeader from "../components/authHeader";

const profileSlice = createSlice({
    name: 'profile',
    initialState: {
        profileDetails: [],
    },
    reducers: {
        setProfileDetails: (state, action) => {
            state.profileDetails = action.payload;
            //return { profileDetails: action.payload };
        },
    }
});

export const getProfileDetails = (dispatch) => {
    axios.get(urls.user_details, { headers: authHeader() }).then((response) => {
        dispatch(setProfileDetails(response.data.results[0]));
    }).catch(e => {
        console.log(e);
    });
}

export const { setProfileDetails } = profileSlice.actions;
export default profileSlice.reducer;


Solution 1:[1]

A reducer must always return a new object, so your commented version was actually better. Better still would be something like this:

const profileSlice = createSlice({
  name: 'profile',
  initialState: {
    profileDetails: [],
  },
  reducers: {
    setProfileDetails: (state, action) => ({ ...state, profileDetails: action.payload }),
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Beto Frega