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"}
]
*/
Related
I am using React with nextJS to do web developer,I want to render a list on my web page, the list information comes from the server(I use axios get function to get the information). However some JSON objects are lack of some information like the name, address and so on. My solution is to use a If- else to handle different kind of JSON object. Here is my code:
getPatientList(currentPage).then((res: any) => {
console.log("Response in ini: " , res);
//console.log(res[0].resource.name[0].given[0]);
const data: any = [];
res.map((patient: any) => {
if ("name" in patient.resource) {
let info = {
id: patient.resource.id,
//name:"test",
name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
} else {
let info = {
id: patient.resource.id,
name: "Unknow",
//name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
}
});
Is there any more clever of efficient way to solve this problem? I am new to TS and React
Use the conditional operator instead to alternate between the possible names. You should also return directly from the .map callback instead of pushing to an outside variable.
getPatientList(currentPage).then((res) => {
const mapped = res.map(({ resource }) => ({
id: resource.id,
// want to correct the spelling below?
name: "name" in resource ? resource.name[0].given[0] : "Unknow",
birthDate: resource.birthDate,
gender: resource.gender,
}));
// do other stuff with mapped
})
This question already has an answer here:
ES6 deep nested object destructuring
(1 answer)
Closed 1 year ago.
I have an Apollo query:
const { error, loading, data: user } = useQuery(resolvers.queries.ReturnUser, {
variables: { userId: parseInt(id) },
});
The data object returned from the query has another object called returnUser. So the actual object is:
data: {
returnUser: {
name: 'Some Name'
}
}
In my JSX I want to output the data:
return (
<div>
{ user ?
<p>Profile {user.returnUser.name}</p> :
<div>User not found</div> }
</div>
);
As you can see I need to access the returnUser object on the user object to get the actual user data. This is not great. Is there any way to destructure the data object from the useQuery so I can assign the nested object to user?
//edit: While this looks like a duplicate question, the answer is different due to the async nature of useQuery. If you don't set a default value you'll get an error.
Got the answer thanks to #Pilchard:
const {error, loading, data: {returnUser: user} = {}} = useQuery(resolvers.queries.ReturnUser, {
variables: {userId: parseInt(id)},
});
You can follow the same nesting while deconstructing the data.
e.g.
const data = {
anotherLevel: {
returnUser: {
name: 'Some Name'
}
}
}
const { anotherLevel: {returnUser: { name }}} = data;
console.log(name); // prints Some Name
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()?
I have this json variable on my state:
this.state = {
type:
{
name: '',
type2: {
atribute: '',
parameter: [
{
value: '',
classtype: ''
}
],
name: '',
atribute1: '',
atribute2: ''
}
}
}
what I wanted to do is to add elements to my parameter list,which is empty on the beggining.
What I did was this:
addParams = () => {
let newParam = {
value: this.state.type.type2.parameter.value,
classtype: this.state.type.type2.parameter.classtype
};
/** */
this.setState(prevState => ({
type: {
// keep all the other key-value pairs of type
...prevState.type,
type2: {
...prevState.type.type2,
//this is supposed to add an element to a list
parameter: [...prevState.type.type2.parameter, newParam]
}
}
}))
}
But when executing the last line of code the following error appeared:
Uncaught TypeError: Invalid attempt to spread non-iterable instance
when spreading a list
I do not know why this does not work because the parameter is a list indeed.
If this.state.type.type2.parameter is an array then why are you referencing properties on it:
let newParam = {
value: this.state.type.type2.parameter.value,
classtype: this.state.type.type2.parameter.classtype
};
I don't think your state is structured how you expect, seems like you're replacing that array with an object at some point in your code. I suggest react-devtools to help you keep track of your state as it changes.
This isn't exactly an answer but I highly suggest using immerjs for doing these pure nested updates. I almost never recommend adding a third party library as a solution but immer is lightweight and life changing. It exports a single function called produce and uses a concept called a Proxy to perform pure updates that are written as mutations.
With immer (and your bug fixed) your code becomes this:
const newParam = {
value: this.state.type.type2.parameter.value,
classtype: this.state.type.type2.parameter.classtype
};
this.setState(produce(draftState => {
draftState.type.type2.parameter.push(newParam);
}))
It lets you write more terse code that is a lot easier to read. And yes I know that looks like a mutation, but it isn't one this is 100% pure.
Try this :
this.setState(prevState => {
return {
...prevState,
type: {
...prevState.type,
type2: {
...prevState.type.type2,
parameter: [...prevState.type.type2.parameter, newParam]
}
}
}
)
I have an app which has a few users. I would now like to be able to create a new user. So I have created this actionCreator:
export const createUser = (first, last) => {
console.log("You are about to create user: XX ");
return {
type: 'USER_CREATE',
first: first,
last: last,
payload: null
}
};
I am dealing only with first & last names for now. The actionCreator gets its parameters from the container. There is a button which calls the actionCreator like so:
<button onClick={() =>this.props.createUser(this.state.inputTextFirstName, this.state.inputTextLastName)}>Submit</button>
My UserReducer looks like this:
/*
* The users reducer will always return an array of users no matter what
* You need to return something, so if there are no users then just return an empty array
* */
export default function (state = null, action) {
if(state==null)
{
state = [
{
id: 1,
first: "Bucky",
last: "Roberts",
age: 71,
description: "Bucky is a React developer and YouTuber",
thumbnail: "http://i.imgur.com/7yUvePI.jpg"
},
{
id: 2,
first: "Joby",
last: "Wasilenko",
age: 27,
description: "Joby loves the Packers, cheese, and turtles.",
thumbnail: "http://i.imgur.com/52xRlm8.png"
},
{
id: 3,
first: "Madison",
last: "Williams",
age: 24,
description: "Madi likes her dog but it is really annoying.",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
}
]
}
switch (action.type) {
case 'USER_DELETED':
return state.filter(user => user.id !== action.userIdToDelete);
case 'USER_CREATE':
console.log("Action first:" + action.first);
console.log("Action last:" + action.last);
Object.assign({}, state, {
id: 4,
first: action.first,
last: action.last,
age: 24,
description: "Some new Text",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
});
return state;
}
return state;
}
Now I have a few questions.
1) Is this the proper way to do this, or am I writing bad code somewhere? Keep in mind that I am trying to use Redux here, I am not entirely sure though whether I am not sometimes falling back into React without Redux
2) Am I doing the state thing correctly? I initially used a tutorial and am now building upon that, but I am not sure why state seems to be an array:
state = [ <--- Does this mean that my state is an array?
{
id: 1,
// and so on ...
I am very confused by this, since in other Tutorials state is just an object containing other smaller objects and its all done with parentheses { }
3) What would be the best way to create a new user. My Object.assign does not work, it does not update anything, and I am not sure where the mistake lies.
4) And, relatedly, how could I update one individual user or a property of one individual user?
As Flyer53 states you need to set the state to the return value of Object.assign() as this is designed to not mutate state it will not change the value of the state you're passing in.
The code's fine; I'd tend to use just one property on the action in addition to its type, so have a property of (say) user that is an object containing all the user data (first name, last name etc).
I believe it's quite idiomatic to define a default state outside of the reducer and then set this as the default value for the state parameter in the reducer function:
export default function (state = initialState, action) {
For a brilliant introduction by its creator, see https://egghead.io/courses/getting-started-with-redux
State can be any shape you like. As an application grows in complexity it will usually be represented as an object composed of different sections of data. So, for example, in your case in could be comprised of an array of users and, say, an 'order by' that could apply to some UI state):
{ users: [], orderBy: 'lastName' }
If you carry on using an array of users as the state then you can use the ES6 spread operator to append the new user, for example:
newState = [ ...state, action.user ];
whereas if you move to using an object for state, the following would similarly append a user:
newState = Object.assign({}, state, { users: [ ...state.users, action.user ] };
Finally, to update a single user you could just use map against the array of users as follows (this is obviously hardcoded, but you could match, say, on id and update the appropriate properties).
let modifiedUsers = state.users.map((user) => {
if (user.id === 3) {
user.name = user.name + '*';
}
return user;
});
let newState = Object.assign({}, state, { users: modifiedUsers });
There's maybe an easier way to log the state(users) in an object (not in an array as in your example code above) that works without Object.assign() which is supposed to work with objects, not arrays:
var state = {
user1: {
id: 1,
first: "Bucky",
last: "Roberts",
age: 71,
description: "Bucky is a React developer and YouTuber",
thumbnail: "http://i.imgur.com/7yUvePI.jpg"
}
};
state['user' + 2] = {
id: 2,
first: "Joby",
last: "Wasilenko",
age: 27,
description: "Joby loves the Packers, cheese, and turtles.",
thumbnail: "http://i.imgur.com/52xRlm8.png"
};
console.log(state);
console.log(state.user2);
Just an idea ...