I need to set state on nested object value that changes dynamically Im not sure how this can be done, this is what Ive tried.
const [userRoles] = useState(null);
const { isLoading, user, error } = useAuth0();
useEffect(() => {
console.log(user);
// const i = Object.values(user).map(value => value.roles);
// ^ this line gives me an react error boundary error
}, [user]);
// This is the provider
<UserProvider
id="1"
email={user?.email}
roles={userRoles}
>
The user object looks like this:
{
name: "GGG",
"website.com": {
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
I need to grab the roles value but its parent, "website.com" changes everytime I call the api so i need to find a way to search for the roles.
I think you need to modify the shape of your object. I find it strange that some keys seem to be fixed, but one seems to be variable. Dynamic keys can be very useful, but this doesn't seem like the right place to use them. I suggest that you change the shape of the user object to something like this:
{
name: "GGG",
site: {
url: "website.com",
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
In your particular use case, fixed keys will save you lots and lots of headaches.
You can search the values for an element with key roles, and if found, return the roles value, otherwise undefined will be returned.
Object.values(user).find(el => el.roles)?.roles;
Note: I totally agree with others that you should seek to normalize your data to not use any dynamically generated property keys.
const user1 = {
name: "GGG",
"website.com": {
roles: ["SuperUser"],
details: {}
},
friends: {},
otherData: {}
}
const user2 = {
name: "GGG",
friends: {},
otherData: {}
}
const roles1 = Object.values(user1).find(el => el.roles)?.roles;
const roles2 = Object.values(user2).find(el => el.roles)?.roles;
console.log(roles1); // ["SuperUser"]
console.log(roles2); // undefined
I would recommend what others have said about not having a dynamic key in your data object.
For updating complex object states I know if you are using React Hooks you can use the spread operator and basically clone the state and update it with an updated version. React hooks: How do I update state on a nested object with useState()?
Related
In this below example, I want add or remove the products array elements from object3 and need to updated in react hooks state.
I have tried with filter method inside setter for deleting an element but it won't work. can anyone pls help to do with efficiently.
const myValue = {
object1: {},
object2: {},
object3: {
products: [{
name: 'Fruits',
id: '1'
},
{
name: "Vegtables",
id: '2'
}],
number: 1
}
}
You can extract out the object3 as another variable, do whatever operations you want to do and set state again combining it with the current state value.
const {object3} = myValue;
// for example if you want to filter based on condition for id
const modifiedProducts = object3.products.filter((item) => item.id > '1');
setMyValue({
...myValue,
object3: {
...object3,
products: modifiedProducts
}
})
I would also suggest making multiple states for each object if all objects are independent from each other. Here if some component only depends on object1, ideally it should not re render when object 3 updates.
I have the following state.
state = {
friends: {
nickNames: ['Polly', 'P', 'Pau'],
... here more k:v
},
}
}
And I want to update nickNames array with a value coming from an uncontrolled form through a method in my class. However, I'm having issues at the time of determine if I am setting the state properly without mutating it.
I am doing the following
updateArray = (nickName) => {
const tempDeepCopy = {
...this.state,
friends: {
...this.state.friends,
nickNames: [...this.state.friends.nickNames]
}
}
tempDeepCopy.friends.nickNames.push(nickName)
this.setState({
friends:
{
nickNames: tempDeepCopy.friends.nickNames
}
})
}
Is this the proper way of doing it? If so, is it also the most efficient given the state? I am trying to avoid helper libraries to learn how to make deep copies.
I will appreciate help since Im trying to learn immutability and it is a concept that is taking me a lot of effort.
setState() in class components does shallow merge.
So you could just ignore other "parent" keys and focus only on friends.
You can also simplify it like:
this.setState({
friends: { // only focus on friends
...this.state.friends, // do not ignore other friend k:v pairs
nicknames: [
...this.state.friends.nicknames,
nickName
]
}
})
Why not just;
updateArray = (nickName) => {
const updatedNickNames = [...this.state.friends.nickNames, nickName];
this.setState({
friends: {
...this.state.friends,
nickNames: updatedNickNames
}
});
}
Because nickNames is just a array of strings, you can copy it with the spread operator. Also, with setState you can change a specific part of your state, in your case you only have to worry about the friends part.
You can just use
this.setState({
friends:
{
nickNames: [...this.state.friends.nickNames, nickName]
}
})
State should be only modified through the setState function because if you modify it directly you could break the React component lyfecycle.
It is a correct way to do that. The thing is you must never change the state directly. That is it.
I might give a more concise code
state = {
friends: {
nickNames: ['Polly', 'P', 'Pau'],
... here more k:v
},
}
}
updateArray = (nickName) => {
this.setState(prevState => ({
...prevState,
friends:
{
...prevState.friends,
nickNames: [...prevState.friends.nickNames, nickname]
}
}))
}
As long as you do not change the state directly, any way will do through setState()
I cannot seem to find an answer on here that is relevant to this scenario.
I have my state in my React component:
this.state = {
clubs: [
{
teamId: null,
teamName: null,
teamCrest: null,
gamesPlayed: []
}
]
}
I receive some data through API request and I update only some of the state, like this:
this.setState((currentState) => {
return {
clubs: currentState.clubs.concat([{
teamId: team.id,
teamName: team.shortName,
teamCrest: team.crestUrl
}]),
}
});
Later on I want to modify the state value of one of the properties values - the gamesPlayed value.
How do I go about doing this?
If I apply the same method as above it just adds extra objects in to the array, I can't seem to target that specific objects property.
I am aiming to maintain the objects in the clubs array, but modify the gamesPlayed property.
Essentially I want to do something like:
clubs: currentState.clubs[ index ].gamesPlayed = 'something';
But this doesn't work and I am not sure why.
Cus you are using concat() function which add new item in array.
You can use findIndex to find the index in the array of the objects and replace it as required:
Solution:
this.setState((currentState) => {
var foundIndex = currentState.clubs.findIndex(x => x.id == team.id);
currentState.clubs[foundIndex] = team;
return clubs: currentState.clubs
});
I would change how your state is structured. As teamId is unique in the array, I would change it to an object.
clubs = {
teamId: {
teamName,
teamCrest,
gamesPlayed
}
}
You can then update your state like this:
addClub(team) {
this.setState(prevState => ({
clubs: {
[team.id]: {
teamName: team.shortName,
teamCrest: teamCrestUrl
},
...prevState.clubs
}
}));
}
updateClub(teamId, gamesPlayed) {
this.setState(prevState => ({
clubs: {
[teamId]: {
...prevState.clubs[teamId],
gamesPlayed: gamesPlayed
},
...prevState.clubs
}
}));
}
This avoids having to find through the array for the team. You can just select it from the object.
You can convert it back into an array as needed, like this:
Object.keys(clubs).map(key => ({
teamId: key,
...teams[key]
}))
The way I approach this is JSON.parse && JSON.stringify to make a deep copy of the part of state I want to change, make the changes with that copy and update the state from there.
The only drawback from using JSON is that you do not copy functions and references, keep that in mind.
For your example, to modify the gamesPlayed property:
let newClubs = JSON.parse(JSON.stringify(this.state.clubs))
newClubs.find(x => x.id === team.id).gamesPlayed.concat([gamesPlayedData])
this.setState({clubs: newClubs})
I am assuming you want to append new gamesPlayedData each time from your API where you are given a team.id along with that data.
I have associative array.
It's a key(number) and value(object).
I need to keep state of this array same as it is I just need to update one object property.
Example of array:
5678: {OrderId: 1, Title: "Example 1", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
5679: {OrderId: 2, Title: "Example 2", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
I need to update Users array property.
I tried this but it doesn't work:
ordersAssociativeArray: {
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
}
This is data inside reducer.
What I did wrong how to fix this?
Something that might help.
When I inspect values in chrome I check previous value and value after execution of my code above:
Before:
ordersAssociativeArray:Array(22) > 5678: Order {OrderId: ...}
After:
ordersAssociativeArray: > 5678: {OrderId: ...}
Solution (code in my reducer)
let temp = Object.assign([], state.ordersAssociativeArray);
temp[action.key].Users = action.updatedUsers;
return {
...state,
ordersAssociativeArray: temp
}
So this code is working fine.
But I still don't understand why? So I have solution but would like if someone can explain me why this way is working and first not?
If it could help here how I put objects in this associative array initialy:
ordersAssociativeArray[someID] = someObject // this object is created by 'new Order(par1, par2 etc.)'
What you are doing is correct, as demonstrated by this fiddle. There may be problem somewhere else in your code.
Something that I would recommend for you is to separate your reducer into two functions, ordersReducer and orderReducer. This way you will avoid the excessive use of dots, which may be what caused you to doubt the correctness of your code.
For example, something like:
const ordersReducer = (state, action) => {
const order = state[action.key]
return {
...state,
[action.key]: orderReducer(order, action)
}
}
const orderReducer = (state, action) => {
return {
...state,
Users: action.updatedUsers
}
}
I hope you find your bug!
Update
In your solution you use let temp = Object.assign([], state.ordersAssociativeArray);. This is fine, but I thought you should know that it is sometimes preferable to use a {} even when you are indexing by numbers.
Arrays in javascript aren't great for representing normalized data, because if an id is missing the js array will still have an undefined entry at that index. For example,
const orders = []
array[5000] = 1 // now my array has 4999 undefined entries
If you use an object with integer keys, on the other hand, you get nice tightly packed entries.
const orders = {}
orders[5000] = 1 // { 5000: 1 } no undefined entries
Here is an article about normalizing state shape in redux. Notice how they migrate from using an array in the original example, to an object with keys like users1.
The problem can be that you're using array in the state but in the reducer you're putting as object. Try doing:
ordersAssociativeArray: [ //an array and not an object
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
]
It will put ordersAssociative array in your state and not an object.
Okay, here's the pickle that I'm in, one of my actions in actions/index.js is:
export function requestPeople() {
return (dispatch, getState) => {
dispatch({
type: REQUEST_PEOPLE,
})
const persistedState = loadState() // just loading from localStorage for now
console.log(persistedState)
//Object.keys(persistedState).forEach(function(i) {
//var attribute = i.getAttribute('id')
//console.log('test', i,': ', persistedState[i])
//myArr.push(persistedState[i])
//})
//console.log(myArr)
//dispatch(receivePeople(persistedState)) // I'm stuck here
}
}
and when I console.log(persistedState) from above in the Chrome console I get my people state exactly like this.
Object {people: Object}
Then when I drill down into people: Object above, I get them like this:
abc123: Object
abc124: Object
abc125: Object
and when I drill down into each one of these puppies (by clicking on the little triangle in Chrome console) I get each like this:
abc123: Object
firstName: 'Gus'
id: 'abc123'
lastName: 'McCrae'
// when I drill down into the second one I get
abc124: Object
firstName: 'Woodrow'
id: 'abc124'
lastName: 'Call'
Now, here's where I'm stuck.
The table I'm using is Allen Fang's react-bootstrap-table which only accepts array's, and it get's called like this <BootstrapTable data={people} /> so my above data needs to be converted to an array like this:
const people = [{
id: abc123,
firstName: 'Gus',
lastName: 'McCrae'
}, {
id: abc124,
firstName: 'Woodrow',
lastName: 'Call'
}, {
...
}]
// and eventually I'll call <BootstrapTable data={people} />
My question specifically is how do I convert my people state shown above into this necessary array? In my action/index.js file I've tried: Object.keys(everything!!!)
And lastly, once I have the array, what's the best way to pass that array into <BootstrapTable data={here} /> using state, a variable, a dispatched action, something I've never heard of yet?
Any help will be very much appreciated!! FYI, this is my first question in Stack Overflow, feels nostalgic. I'm a full-time police officer, and trying learn to code on the side. Thanks again!
UPDATE:
Thanks to a suggestion by Piotr Berebecki, I'm tying it this way:
export function requestPeople() {
return (dispatch, getState) => {
dispatch({
type: REQUEST_PEOPLE,
})
const persistedState = loadState()
console.log('persistedState:', persistedState)
const peopleArr = Object.keys(persistedState.people).map(function(key) {
return persistedState[key]
})
console.log(JSON.stringify(peopleArr))
//dispatch(receivePeople(persistedState))
}
}
and getting [null,null,null]
like this:
Welcome to Stack Overflow :)
To convert your nested persistedState.people object to an array you can first establish an interim array of keys using Object.keys(persistedState.people) and then map() over the keys to replace each key with an object found in your original nested object - persistedState.people - at that key. You can assign the resultant array to a variable which you can then pass to the BootstrapTable. Check the code below and a demo here: http://codepen.io/PiotrBerebecki/pen/yaXrVJ
const persistedState = {
people: {
'abc123' : {
id:'abc123',firstName: 'Gus', lastName: 'McCrae'
},
'abc124' : {
id:'abc124',firstName: 'Woodrow', lastName: 'Call'
},
'abc125' : {
id:'abc125',firstName: 'Jake', lastName: 'Spoon'
}
}
}
const peopleArr = Object.keys(persistedState.people).map(function(key) {
return persistedState.people[key];
});
console.log(JSON.stringify(peopleArr));
/*
Logs the following array:
[
{"id":"abc123","firstName":"Gus","lastName":"McCrae"},
{"id":"abc124","firstName":"Woodrow","lastName":"Call"},
{"id":"abc125","firstName":"Jake","lastName":"Spoon"}
]
*/