Skip to content

Proper Way To Get Current State With Immer ? #1134

Open
@chalu

Description

@chalu

🙋‍♂ Proper Way To Get Current State

What is the proper way of getting the current state with immer. Do you reassign the output of produce to the state or use something else like "current" which can be imported from the immer package?

Does reassigning not negate the immutability practice of Immer, especially if using Typescript and the state was defined as read-only to enforce immutability. This has not been clear to me from the documentation, hence the question :

import { produce } from "immer";

type AppState = {
    readonly photos: string[];
};

// should state not be read-only and declared with const?
let state: AppState = {
    cards: []
};

// get photos straight from the state at any time. 
// what's the right way??
export const getPhotos = () => state.photos;

export const addPhotos = (...recents: string[]) => {
   // re-assigning state here so we can use its latest update ??
    state = produce(state, (draft) => {
        draft.photos.push(...recents);
    });
    return state.photos;
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions