question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React Hook does not update on state update

See original GitHub issue

Hey there, I have been using zustand.js so far but there is a case where the html does not update when the state changes. My Code:

NotesList.js:

import React, { Component, useState } from 'react';

import {useNotes} from '../store.js';

const NotesList = () => {
    let notes = useNotes(state => state.data.notes);
    let changeCurrentNote = useNotes(state => state.changeCurrentNote);


  //  let uuidNote = useNotes(state => state.data.notes.uuid.title);
    const selectNote = (e) => {
        let note_id = e.target.id.split('-')[1];
        changeCurrentNote(note_id);
    }

    return(
    <div className="notes">
       {
       Object.entries(notes).map((note, key) => { // note[0] = id, note[1].content, note[1].title etc
           return (<div id={'note-' + note[0]} key={note[0]} onClick={selectNote}>{note[1].title}</div>)
       })
    }

    </div>
    )
}
export default NotesList

A part of store.js:

const [useNotes] = create((set, get) => ({
    data: {
        notes: {
            uuid: {
                content: "Just a Note.",
                title: "A Note here...",
                tags: ["Abc"]
            },
        }
  }
}
export {useNotes}

However, if I add let uuidNote = useNotes(state => state.data.notes.uuid.title); in the Hook the specific title does update (other titles don’t), is there a way to fix that / am I doing someting wrong?

Edit: it works if I use the following save() function (inside create() )`

save: () => {
   
            let oldState = get().data.notes;
 
            
            let currentNote = get().data.currentNote;

            oldState[currentNote.id].title = currentNote.title;
            oldState[currentNote.id].content = currentNote.content;
            oldState[currentNote.id].tags = currentNote.tags;

            set(state => {
                state.data.notes = null // it does not work if I remove this line
            });
            set(state => {
                state.data.notes = oldState
            })
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
dai-shicommented, Aug 26, 2020

Glad it worked well.

        set(state => {
            state.data = newState
       });

This is not correct. Please do it like below:

        set({ data: newState })
        set(state => ({ data: newState })) // this works too
        set(state => ({ ...state, data: newState })) // this works too

Otherwise, useStore() with no selector won’t work.

maybe just the immerjs example provided in the docs

Do you mean like this?

import produce from 'immer'

const useStore = create(set => ({
  lush: { forrest: { contains: { a: "bear" } } },
  setWithImmer: fn => set(produce(fn)),
}))

const setWithImmer = useStore(state => state.setWithImmer)
setWithImmer(state => {
  state.lush.forrest.contains = null
})

It looks a bit verbose.

import produce from 'immer'

const useStore = create(origSet => ({
  lush: { forrest: { contains: { a: "bear" } } },
  set: fn => origSet(produce(fn)),
}))

const set = useStore(state => state.set)
set(state => {
  state.lush.forrest.contains = null
})

A little better, but still. I personally don’t think it’s worth it either way…

1reaction
dai-shicommented, Aug 25, 2020

Thanks.

    changeCurrentNote: (id) => {
        set(state => ({
            data: {
              ...state.data,
              currentNode: {
                id,
                title: state.data.notes[id].title,
                content: state.data.notes[id].content,
                tags: state.data.notes[id].tags,
              }
           }
        }));

this should fix.

If you prefer mutating syntax, consider using immer.

Read more comments on GitHub >

github_iconTop Results From Across the Web

The useState set method is not reflecting a change immediately
Component or React.PureComponent , the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately....
Read more >
React setState does not immediately update the state - Medium
useState React hook. Returns a stateful value, and a function to update it. The function to update the state can be called with...
Read more >
Why React doesn't update state immediately - LogRocket Blog
State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The ......
Read more >
Steps to Solve Changes Not Reflecting When useState Set ...
When the “useState” set method is not reflecting a change immediately, it may be due to the current closure of the state variable....
Read more >
Why React setState/useState does not update immediately
The answer: They're just queues ... React this.setState , and useState does not make changes directly to the state object. React this.setState ,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found