How to add and update json array elements using react hooks - reactjs

I defined a state with null array, Then that array will contain firstname, lastname etc..based on entry in text field. I need to add the prop if not present and update the prop if present. I need to do validation in save based on that. I tried with below code, but that not works.
const [signerData, setSignerData] = useState([]);
const newItems = [...signerData];
newItems["firstName"] = inputValue;
setSignerData({ newItems });
Any help is appreciated. Thank you.

Firstly, you would need an object instead of an array. Array doesn't allow you to have keys, only values. The below code would work.
const [signerData, setSignerData] = useState({});
setSignerData({ ...signerData, firstName: inputValue });

Related

Why I cannot map data?

I'm trying to map "historicData" and put them in the labels of chart but it gives me error,"u cannot map the undefined".
So,Error is historicData is undefined .When I console.log(historicData),there is an array data.
This is my Code.
https://github.com/Saithiha24/React-Crypto-Beast/blob/master/src/Components/CoinInfo.js
I try to solve this for 2 days still can't find the answer. Please help me.
I think the problem is that historicData is initially undefined, and while waiting for the async call to complete and give historicData a value, you get the error. I suggest you change this
const [historicData, setHistoricData] = useState();
to this
const [historicData, setHistoricData] = useState([]);
so historicData is originally an empty array instead of undefined. You can also change the definition of data likes this
const data = {
labels: historicData ? historicData.map((coin) => {
//your code
}) : []}
so that if historicData is undefined, you don't try to map, just assign an empty array to labels.

how can i get the information inside react js object

how can I access the name inside the object and put it inside a variable
const newItem = [...items].filter((item) => id === item.id);
const comments = newItem.price;
console.log([newItem.price]);
I tried this one but didn't work, console says undefined
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
filter() method
You can get price by usign the below way.
const newItem = [...items].filter((item) => id===item.id);
const comments= newItem[0].price;
console.log(newItem[0].price)

How to mutate an object inside array in react.js state?

I have an issue when i trying to updating the state.
here is my code:
const [todos, setTodos]= useState([])
useEffect(() => {
setTodos([
{id:1, title: '',
notes: [{id: 1, description: 'this is a simple description'}]}
])
}, [])
my goal is to add a note to the array of todos.
i try like this
const i = todos.findIndex((t) => t.id === parseInt(id));
const newArr = todos[i].notes[0].push(note);
setTasks(newArr);
but it's not working the newArr gives me the index note the new state.
Please help
Thanks in advance
if you want to get it working you can do something like below:
const newArr = todos[i].notes.push(note)
but it's not the recommended way.
The best way to add new item in to your notes array is to use object.assign or spread operator in order to not directly mutate your entire array. some thing like below:
const newArr = [...todos[i], note]
and also use this way of mutating your entire tasks array.
I think it's been well-described ar here if you want to get more information around why you should use spread operator instead of push.
I have created this which works perfectly. What you have to do is to obtain the todo id and push to its note. Here the todo state gets updated but render method is not called. In order to call the render method I have called setTodo again.

Adding an element to an existing array in react hooks

So I have this state variable:
const [Class, setClass] = useState({ Teacher: "John Fartsalot", Year: 2021, Students: [] });
and I have a:
ver studentObject
I want to push the studentObject into the Students array dynamically using setClass.
I came across this post: Push method in React Hooks (useState)? but it seems to be relevant only when there's just the list in there.
What is the correct way to do so in my case?
While you could spread the existing Class into a new object, and then spread the new students array into that new object as well, it would be better to follow the convention and separate out the state variables (as React recommends), and to not use Class as a variable name (it's very close to the reserved word class). Consider:
const [teacher, setTeacher] = useState('John Fartsalot');
const [year, setYear] = useState(2021);
const [students, setStudents] = useState([]);
Then to add to the students array, do
setStudents([...students, studentObject]);
Or, if students happens to be in a stale closure at this point, then
setStudents(students => [...students, studentObject]);
This is correct way to add:
setStudents(students => [...students, studentObject]);

Object properties being assigned to a form show up as object Object instead of the actual value

I'm passing an object called "team" to this function in React. The "team" object has 4 different properties.
id, playerName, typeId, and locationName.
I am populating state values like this:
const [idValue, setIdValue] = React.useState(false);
const [typeIdValue, setTypeIdValue] = React.useState(false);
const [nameValue, setNameValue] = React.useState(false);
const [locationValue, setLocationValue] = React.useState(false);
And my function looks like this that sets the state values above.
const showEdit = (team) => {
console.log(team);
setShowRosterForm(true);
setIdValue(team.id);
setTypeIdValue(team.typeId);
setNameValue(team.playerName);
setLocationValue(team.locationName);
}
I then display these values in a form like this:
const RosterForm = ({
idValue, typeIdValue, nameValue, locationValue
}) => ( ... display form fields )
But when I populate the form with these values, I just see [object Object].
But I don't understand that, because when I wite out the 'team' object to the console, I can see all the individual properties like id, typeId, playerName, and locationName.
So I'm not sure why it's an Object.
Is there a better way of going about doing this?
Thanks!
You do not need to pass in the state getters into your RosterForm(). Can you not directly use the getters typeIdValue and others to set the form?
Please print a console.log(typeIdValue) inside your RosterForm() so that you can see the value it receives.
I believe the setting of the values to the form might be incorrect. Could you update your code for setting the value to a field of your form?

Resources