Skip to content
Advertisement

How to get updated redux-toolkit state when component is not re-render

I’m trying to delete item in redux toolkit, but don’t know how, the remove function only work on screen, i have to press twice to delete the previous one

Here is the reducer

const noteReducer = createSlice({
  name: "note",
  initialState: NoteList,
  reducers: {
    addNote: (state, action: PayloadAction<NoteI>) => {
      const newNote: NoteI = {
        id: new Date(),
        header: action.payload.header,
        note: action.payload.note,
        date: new Date(),
        selectStatus: false,
      };
      state.push(newNote);
    },
    removeNote: (state, action: PayloadAction<NoteI>) => { // 
 ======> Problem here
      return state.filter((item) => item.id !== action.payload.id);
    },
    toggleSelect: (state, action: PayloadAction<NoteI>) => {
      return state.map((item) => {
        if (item.id === action.payload.id) {
          return { ...item, selectStatus: !item.selectStatus };
        }
        return item;
      });
    },
    loadDefault: (state) => {
      return state.map((item) => {
        return { ...item, selectStatus: false };
      });
    },
    resetNote: (state) => {
      return (state = []);
    },

    editNote: (state, action: PayloadAction<NoteI>) => {
      return state.map((item) => {
        if (item.id === action.payload.id) {
          return {
            ...item,
            note: action.payload.note,
            header: action.payload.header,
            date: action.payload.date,
          };
        }
        return item;
      });
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchNote.fulfilled, (state, action) => {
      state = [];
      return state.concat(action.payload);
     
    });
    
  },
});

Here is the function where i use it: CODE UPDATED

export default function NoteList(props: noteListI) {
  const { title, note, id, date } = props;
  const data = useSelector((state: RootState) => state.persistedReducer.note);
   useEffect(() => {
    currentDate.current = data;
  }, [data]);
  const removeSelectedNote = () => {
    dispatch(removeNote({ id: id }));
    console.log(data);  ====> still log 4 if i have 4
  };
 console.log(data); // ====> work if i log here but a lots of logs

  return (
    <View>
      <TouchableOpacity
        onLongPress={() => {
          removeSelectedNote();
          console.log("current", currentDate.current);   ///same
        }}
        // flex
        style={CONTAINER}
        onPress={() =>
          !toggleSelectedButton ? onNavDetail() : setEnableToggle()
        }
      >
        <Note
          note={note}
          header={title}
          date={date}
          id={id}
          selectedStatus={selectedButtonStatus}
        />
      </TouchableOpacity>
    </View>
  );
}

I have to press twice to make it work, for example, i have 4 item, when i press one, the item on screen disappears but the data log still have 4 item, when i click another, it show 3 on console.log but the screen display 2, the redux state is change outside the return() but i can’t capture the updated state, it work the previous one

Here is a gif to show what going on

enter image description here

When i press only one item, it change on UI but when i refresh it return same state

enter image description here

When i click twice or more, it make changes to previous enter image description here

Updated

The redux-persist code:

const reducer = combineReducers({
  note: noteReducer,
  firebase: authentication,
});
const persistConfig = {
  key: "root",
  storage: AsyncStorage,
  blacklist: [],
};

const persistedReducer = persistReducer(persistConfig, reducer);
const store = configureStore({
  reducer: { persistedReducer, toggle: toggleReducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

export default store;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const persistStorageNote = persistStore(store);

I also added the useEffect by this, but problem is when i log the changes in function, it remain the same:

enter image description here

Advertisement

Answer

here is how you can log updated data correctly, as state update is asynchronous it doesn’t change immediately when you dispatch removeNote

export default function NoteList(props: noteListI) {
  const { title, note, id, date } = props;
  const data = useSelector((state: RootState) => state.persistedReducer.note);
  // log changed data
   useEffect(() => {
     console.log(data); 
  }, [data]);
  const removeSelectedNote = () => {
    dispatch(removeNote({ id: id }));
  };
 

  return (
    <View>
      <TouchableOpacity
        onLongPress={() => {
          removeSelectedNote();
        }}
        // flex
        style={CONTAINER}
        onPress={() =>
          !toggleSelectedButton ? onNavDetail() : setEnableToggle()
        }
      >
        <Note
          note={note}
          header={title}
          date={date}
          id={id}
          selectedStatus={selectedButtonStatus}
        />
      </TouchableOpacity>
    </View>
  );
}

about reloading issue, try to close the app and open it like a user of your app would (minimize the app -> remove the app from recently opened apps -> open app again ) , instead of reloading the project.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement