immerjs / immerjs/immer

Proper Way To Get Current State With Immer ?

Open
#1,134 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
JavaScript
Stars
29k
Forks
881
PR merge metrics
No merged PRs in 30d

Description

🙋‍♂ 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;
};

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review the issue's questions about produce, current, reassignment, and readonly TypeScript state. Clarify the recommended way to read the current state and whether reassigning the result of produce preserves Immer's immutability model; done means the documentation explicitly answers these cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.