2

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?

Hang Lin
  • 57
  • 6

1 Answers1

3

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 .

markerikson
  • 42,022
  • 7
  • 87
  • 109
  • thanks, so my code works, just didn't like the data being pushed into the array. Objects are not valid as a React child (found: object with keys {date, time, unixTimestamp}) – Hang Lin Dec 04 '20 at 22:46
  • 1
    That's not a Redux thing, that's an issue with how you're rendering in your React component. React won't let you do `
    {someObject}
    `. You can only pass primitive values as the variables in JSX output, like `
    {someObject.name}
    `. Fixing your rendering logic will solve that error.
    – markerikson Dec 05 '20 at 04:00