1const {useState, useCallback} = React;
2function Example() {
3 const [theArray, setTheArray] = useState([]);
4 const addEntryClick = () => {
5 setTheArray([...theArray, `Entry ${theArray.length}`]);
6 };
7 return [
8 <input type="button" onClick={addEntryClick} value="Add" />,
9 <div>{theArray.map(entry =>
10 <div>{entry}</div>
11 )}
12 </div>
13 ];
14}
15
16ReactDOM.render(
17 <Example />,
18 document.getElementById("root")
19);
1const[array,setArray]= useState([
2 {id: 1, value: "a string", othervalue: ""},
3 {id: 2, value: "another string", othervalue: ""},
4 {id: 3, value: "a string", othervalue: ""},
5 ])
6
7const updateItem =(id, whichvalue, newvalue)=> {
8 var index = array.findIndex(x=> x.id === id);
9
10 let g = array[index]
11 g[whichvalue] = newvalue
12 if (index === -1){
13 // handle error
14 console.log('no match')
15 }
16 else
17 setArray([
18 ...array.slice(0,index),
19 g,
20 ...array.slice(index+1)
21 ]
22 );
23}
24//how to use the function
25onPress={()=>updateItem(2,'value','ewfwf')}
26onPress={()=>updateItem(1,'othervalue','ewfwf')}
27/*
28the first input of the function is the id of the item
29the second input of the function is the atrribute that you wish to change
30the third input of the function is the new value for that attribute
31It's a pleasure :0
32~atlas
33*/
1// sample datas structure
2/* const datas = [
3 {
4 id: 1,
5 name: 'john',
6 gender: 'm'
7 }
8 {
9 id: 2,
10 name: 'mary',
11 gender: 'f'
12 }
13] */ // make sure to set the default value in the useState call (I already fixed it)
14
15const [datas, setDatas] = useState([
16 {
17 id: 1,
18 name: 'john',
19 gender: 'm'
20 }
21 {
22 id: 2,
23 name: 'mary',
24 gender: 'f'
25 }
26]);
27
28const updateFieldChanged = index => e => {
29
30 console.log('index: ' + index);
31 console.log('property name: '+ e.target.name);
32 let newArr = [...datas]; // copying the old datas array
33 newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to
34
35 setDatas(newArr); // ??
36}
37
38return (
39 <React.Fragment>
40 { datas.map( (data, index) => {
41 <li key={data.name}>
42 <input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)} />
43 </li>
44 })
45 }
46 </React.Fragment>
47)
48