Title: React Hooks createContext: How to update UserContext when its an array?
Tags: reactjs;react-hooks;react-context
Question: I have state in my UserContext component:
var initialState = {
avatar: '/static/uploads/profile-avatars/placeholder.jpg',
markers: []
var UserContext = React.createContext();
function setLocalStorage(key, value) {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (errors) {
// catch possible errors:
console.log(errors);
function getLocalStorage(key, initialValue) {
try {
const value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : initialValue;
} catch (e) {
// if error, return initial value
return initialValue;
function UserProvider({ children }) {
const [user, setUser] = useState(() =&gt; getLocalStorage('user', initialState));
const [isAvatarUploading, setIsAvatarUploading] = useState(true);
And returning a function to update the array:
return (
<UserContext.Provider
value={{
userMarkers: user.markers,
setUserMarkers: markers =&gt; setUser({ ...user, markers }),
}}
&gt;
{children}
</UserContext.Provider&gt;
In my consuming function I am trying to use that function to add an object to the initial array i.e. markers.
export default function MyMap() {
var { userMarkers, setUserMarkers } = useContext(UserContext);
imagine there is an operation above which changes this value:
setUserMarkers({&quot;id&quot;:1,&quot;lat&quot;:40.73977053760343,&quot;lng&quot;:-73.55357676744462});
What is happening is the old object get completely overridden. so the array gets updated with a new object. Not added. Please help. I also tried concat and it didn't work?
setUserMarkers: markers =&gt; setUser(()=&gt; user.markers.concat(markers)),
So markers should be:
markers: [{&quot;id&quot;:0,&quot;lat&quot;:40.73977033730345,&quot;lng&quot;:-66.55357676744462},{&quot;id&quot;:1,&quot;lat&quot;:40.73977053760343,&quot;lng&quot;:-73.55357676744462}]
Comment: You need to pass an array to `setUserMarkers` when you use `concat`.

Comment: @super thank you for responding, could you provide an example?

Here is the accepted answer: Call your function like this to take the previous value and append to it.
setUserMarkers([...userMarkers, {&quot;id&quot;:1,&quot;lat&quot;:40.73977053760343,&quot;lng&quot;:-73.55357676744462}])
You could also update your function call to always append if you never need to overwrite values in it. Then you can just call it with the new value.
setUserMarkers: markers =&gt; setUser({ ...user, markers: [...user.markers, markers] }),


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:12/15/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<reactjs><react-hooks><react-context>', 'Title': 'React Hooks createContext: How to update UserContext when its an array?', 'ViewCount': 168, 'id': 65314050, 'user_AboutMe': '<p>Hi all!</p>\n\n<p>I am currently a full-time Web Developer who lives in Queens NYC! I love running and spending time with my rascally little daughter!</p>\n\n<p>:)</p>\n', 'user_AccountId': 1383310.0, 'user_DisplayName': 'Antonio Pavicevac-Ortiz', 'user_Reputation': 6411.0, 'user_Views': 1088.0, 'user_id': 1315857.0}}