Redux-toolkit: Assign to initialState object

Created on 21 Feb 2020  路  2Comments  路  Source: reduxjs/redux-toolkit

Hello! im having problems when trying to assign a new object to my initialState empty object like this

const ajustesSlice = createSlice({
    name: 'ajustes',
    initialState: {},
    reducers: {
        setAjustes(state, action) {
            state = action.payload;
        }
    }
});

export const {setAjustes} = ajustesSlice.actions;

export const fetchAjustes = () => async dispatch => {
    const response = await http.get('/centro-ajustes/retrieve/');
    dispatch(setAjustes(response.data));
    return response.data;
};

And when calling fetchAjustes in useEffect hook it just doesn't update the initialState at all.

const dispatch = useDispatch();

useEffect(() => {
        dispatch(fetchAjustes());
    }, []);

The payload is printing exactly what im expecting in the console, but it just doesn't update the initialState object.

Am I doing something wrong?

Does anyone know why? thanks in advance.

Most helpful comment

state = action.payload; this is your problem: RTK can detect if you assign stuff to properties of your state, but completely replacing the whole variable is something we cannot observe.
If you want to replace the whole state, just return the new state.

All 2 comments

state = action.payload; this is your problem: RTK can detect if you assign stuff to properties of your state, but completely replacing the whole variable is something we cannot observe.
If you want to replace the whole state, just return the new state.

state = action.payload; this is your problem: RTK can detect if you assign stuff to properties of your state, but completely replacing the whole variable is something we cannot observe.
If you want to replace the whole state, just return the new state.

Cool, thank u very much sir! closing :)

Was this page helpful?
0 / 5 - 0 ratings