Home > Blockchain >  react functional component state object not rendering in display on change
react functional component state object not rendering in display on change

Time:01-17

I am trying to make a react example project with a way to add a 'project', edit its contents, view, and delete it. Just to practice with setting/changing/saving data.

I'm debating if I should make this as a functional or class component, so currently I am trying with a functional component below:

enter image description here

CodePudding user response:

Interesting question you have here. Your use of functional components isn't really flawed. It looks like you're getting caught on a reference issue.

Your <div> with the project count isn't updating because React doesn't know it needs to update it. React doesn't know it needs to update it because the reference to your projects object isn't changing. If you're confused, just search through articles on object reference equality in JavaScript.

Long story short, your issue is with this line:

let oldProjects = projects;

A quick fix would be to do this:

let oldProjects = { ...projects };

...or this to save a few lines:

setProjects(oldProjects => ({ ...oldProjects, [id]: newProject }));

There are performance reasons why these are not flawless solutions, but if this is just to get the hang of things, I don' think it's a problem.

  • Related