Reputation: 63
i have the following code:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { client } from '../../api/client';
const initialState = {
logBook: [],
status: 'idle',
error: null
};
export const logNewEntry = createAsyncThunk(
'logBook/addNewEntry',
async (logEntry) => {
const response = await client.post('/testPost', logEntry);
console.log('post done');
return response.data;
}
);
const logBookSlice = createSlice({
name: 'logBook',
initialState,
// non async calls
reducers: {},
},
// async calls
extraReducers: {
[logNewEntry.fulfilled] : (state, action) => {
console.log('add to list');
console.log(state);
console.log(action);
state.logBook.push(action.payload);
},
},
})
//export const {resetName} = logBookSlice.actions;
export default logBookSlice.reducer;
export const selectLogBook = (state) => state.logBook.logBook;
the console.log(state);
is not referencing the state of the logBook and therefor I can't add the new entry to it. What console prints:
Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true
I used the reduc template's counterSlice as an example to build this, and their works.
incrementByAmount: (state, action) => {
state.value += action.payload;
},
what am I doing wrong?
Upvotes: 2
Views: 1801
Reputation: 67469
Redux Toolkit uses Immer inside of createSlice
. Immer wraps your original data in a Proxy object so it can track attempted "mutations".
Unfortunately, this does make logging draft state difficult, because browsers show Proxies in a mostly unreadable format.
The line state.logbook.push(action.payload)
should be valid as-is. However, if you want to log the data more readably, you can use the Immer current
method that we export from RTK, which converts the Proxy-wrapped data back to a plain JS object:
console.log(current(state))
See https://redux-toolkit.js.org/api/other-exports#current .
Upvotes: 7