Created
August 12, 2022 11:22
-
-
Save OkancanCosar/ff9b07689e7e34c4e4b250fb9ac76cdd to your computer and use it in GitHub Desktop.
React object list state manuplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useState} from 'react'; | |
const App = () => { | |
const initialState = [ | |
{id: 1, country: 'Austria'}, | |
{id: 2, country: 'Belgium'}, | |
{id: 3, country: 'Canada'}, | |
]; | |
const [data, setData] = useState(initialState); | |
const updateState = () => { | |
// 👇️ passing function to setData method | |
setData(prevState => { | |
const newState = prevState.map(obj => { | |
// 👇️ if id equals 2, update country property | |
if (obj.id === 2) { | |
return {...obj, country: 'Denmark'}; | |
} | |
// 👇️ otherwise return object as is | |
return obj; | |
}); | |
return newState; | |
}); | |
}; | |
return ( | |
<div> | |
<button onClick={updateState}>Update state</button> | |
{data.map(obj => { | |
return ( | |
<div key={obj.id}> | |
<h2>id: {obj.id}</h2> | |
<h2>country: {obj.country}</h2> | |
<hr /> | |
</div> | |
); | |
})} | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment