Json update with lodash

Actually, I need to fully handle the mysite interface with json objects (React and lodash).

I get the source data through an ajax call, which we say

starred[] //returns empty array from server 

and add new json when the user clicks on an asterisk,

 starred.push({'id':10,'starred':1}); 

if user clicks asterisk again, should be 0

 current_star=_findWhere(starred,{'id':10}); _.set(curren_star,'starred',0); 

but when running console.log

 console.log(starred); //returns [object{'id':10,'starred':0}] 

but in fact, when it repeats, global json is not updated, but I perform some other operations like json,

 console.log(starred); //returns [object{'id':10,'starred':1}] 

How to update global, I want, as soon as I change json, it should be changed ever. Should I get the idea of ​​offering a few improved frameworks for handling json a lot easier.

Thanks before!

+5
source share
1 answer

I think the problem is the change in the initial state. Instead of doing push, you need to do the following fe:

 var state = { starred: [] }; //perform push var newItem = {id:10, starred:1}; state.starred = state.starred.concat(newItem); console.log(state.starred); //{ id: 10, starred: 1 }] var newStarred = _.extend({}, state.starred); var curr = _.findWhere(newStarred, {id: 10}); curr.starred = 0; state = _.extend({}, state, {starred: newStarred}); console.log(state.starred) //{ id: 10, starred: 0 }] 

To solve this problem in a more pleasant way, you need to use either the immutability assistant or the ES6 material, for example: {... state, {starred: []}}, and not renew the new object every time. Or just use response-redux =)

0
source

Source: https://habr.com/ru/post/1239300/


All Articles